我尝试创建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
而不是仅仅分配它。
有人有更好的方法来实现这个目标吗?
答案 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;
}
};
};
})