更新模型中的数据不绑定到控制器

时间:2014-11-18 18:58:48

标签: javascript angularjs angularjs-scope angularjs-service

我试图在我的应用程序中关注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内的UserCtrlselect还是空的......

1 个答案:

答案 0 :(得分:0)

所以这很简单,但我花了好几个小时试图解决它......

这不是AngularJs问题,而是JavaScript闭包问题,

以下解决了我的问题,

app.service('CountriesModel', ['$http', 
function($http) {
    $http.get(baseUrl + 'api/countries').success(function(data) {
        this.countries = data;
    }.bind(this));
}]);