我试图在我的应用程序中关注this pattern,但是我无法让它工作。
CountriesModel.js
app.service('CountriesModel', ['$http',
function($http) {
$http.get(baseUrl + 'api/countries').success(function(data) {
this.countries = data;
});
}]);
UserCtrl.js
app.controller('UserCtrl', ['$scope', 'CountriesModel',
function($scope, CountriesModel) {
$scope.CountriesModel = CountriesModel;
}]);
user.html
<select ng-options="country.iso2 as country.short_name for country in CountriesModel.countries" ng-model="selectedCountry"></select>
现在,在AngularJs检查器插件中,我可以看到countries
内的CountriesModel
已正确抓取,undefined
$scope.CountriesModel
内的UserCtrl
和select
还是空的......
答案 0 :(得分:0)
所以这很简单,但我花了好几个小时试图解决它......
这不是AngularJs问题,而是JavaScript闭包问题,
以下解决了我的问题,
app.service('CountriesModel', ['$http',
function($http) {
$http.get(baseUrl + 'api/countries').success(function(data) {
this.countries = data;
}.bind(this));
}]);