Dalli
Dalli

Reputation: 64

Pass value to factory angularjs

I would like to pass article id from url to factory but I can't get the value from $routeChangeSuccess callback.

myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {

    var article_id = $rootScope.$on('$routeChangeSuccess', function () {
        return $routeParams.id;
    });   

    getArticleById.get(article_id).then(function(data) {
        $scope.articles = data;
    });
});

myApp.factory('getArticleById', function($q, $http) {
    return {
        get: function(article_id) {

            var deferred = $q.defer();
            $http.get('/api/admin/article/edit/'+ article_id).success(function(result) {
                deferred.resolve(result);
            }).error(function(result) {
                deferred.reject(result);
            });
            return deferred.promise;
        }
    }
});

$routeProvider

var myApp = angular.module('myApp',['ngRoute','ui.utils','ngSanitize','ui.tinymce'])
.config(function ($routeProvider, $locationProvider) {
        //configure the routing rules here
        $routeProvider.when('/admin/article/edit/:id', {
            controller: 'editCtrl'
        });

        //routing DOESN'T work without html5Mode
        $locationProvider.html5Mode(true);
    }
);

Upvotes: 0

Views: 314

Answers (2)

XrXr
XrXr

Reputation: 2057

You can just update the articles in the $routeChangeSuccess callback.

myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {

    $rootScope.$on('$routeChangeSuccess', function () {
        getArticleById.get($routeParams.id).then(function(data) {
            $scope.articles = data;
        });
    });   
});

This might cause problems when there is multiple route changes in quick successions. In which case you would need to do some more work.

Upvotes: 1

Angad
Angad

Reputation: 3429

Instead of creating a var named article_id in your controller, simply use the $routeParams.id to pass the value to factory.

  getArticleById.get($routeParams.id).then(function(data) {
            $scope.articles = data;
        });

Upvotes: 1

Related Questions