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

Updating Data In Model Not Binds To Controller

本文关键字:绑定 控制器 数据 模型 更新      更新时间:2023-09-26

我正在尝试在我的应用程序中遵循这种模式,但是我无法让它工作。

国家型号.js

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

用户控制.js

app.controller('UserCtrl', ['$scope', 'CountriesModel',
    function($scope, CountriesModel) {
        $scope.CountriesModel = CountriesModel;
}]);

用户.html

<select ng-options="country.iso2 as country.short_name for country in CountriesModel.countries" ng-model="selectedCountry"></select>

现在在 AngularJs 检查器插件中,我可以看到CountriesModel内部的countries正确获取,但仍然undefined UserCtrl内部的$scope.CountriesModelselect仍然是空的......

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

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

以下解决了我的问题,

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