Angular提供程序返回一个数组

时间:2014-08-14 16:22:22

标签: angularjs

我尝试创建customRoutesProvider,但当我在控制器中请求customerRoutes时,数组始终为空...

angular.module('introToAngularApp')
    .config(function(customRoutesProvider) {
        customRoutesProvider.setRoutes([ /* routes */ ])
    });
    .provider('customRoutes', function() {
        this.customRoutes = [];

        this.setRoutes = function (routes) {
            this.customRoutes = routes;
        };

        this.getRoutes = function() {
            return customRoutes;
        };

        // Method for instantiating
        this.$get = function() {
            var customRoutes = this.customRoutes;

            return {
                getRoutes: function() {
                    return customRoutes;
                }
            };
        };
    })
    .controller('DemoCtrl', function(customRoutes) {
        console.log(customRoutes.getRoutes()); // []
    });

我甚至试图将单个路线推送到this.customRoutes而不是仅仅分配它。

有人有更好的方法来实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

this内的$this.get - getRoutes与其父级不同。 您需要访问的不是this,而是that_this或其他

.provider('customRoutes', function() {
    this.customRoutes = [];

    this.setRoutes = function (routes) {
        this.customRoutes = routes;
    };

    this.getRoutes = function() {
        return customRoutes;
    };

    // Method for instantiating
    var _this = this;
    this.$get = function() {
        return {
            getRoutes: function() {
                return _this.customRoutes;
            }
        };
    };
})

plnkr,http://plnkr.co/edit/YlcYAMp1lHfJ0RaFHlFQ?p=preview