将值传递给工厂angularjs

时间:2015-01-10 23:29:35

标签: javascript angularjs

我想将文章ID从url传递到工厂,但我无法从$routeChangeSuccess回调中获取值。

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);
    }
);

2 个答案:

答案 0 :(得分:1)

不要在控制器中创建名为article_id的var,只需使用$ routeParams.id将值传递给factory。

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

答案 1 :(得分:1)

您只需更新$routeChangeSuccess回调中的文章。

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

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

当快速连续中有多个路径更改时,这可能会导致问题。在这种情况下,您需要做更多的工作。