异步ngOptions

时间:2015-03-18 23:28:29

标签: javascript angularjs asynchronous angularjs-ng-options

说实话,我不知道我在Angular中做了什么,所以这可能是糟糕的编码习惯。无论如何,我试图将一些数据异步加载到<select>元素中。

这是模板HTML:

<div ng-include src="'scripts/common/toolbar/toolbar.html'"></div>
<div class="wrapper">
    <div ng-include src="'scripts/common/header/pageheader.html'"></div>
    <label>Advertisers:
        <select ng-model="selectedAdvertiser" ng-options="adv as adv.name for adv in advertisers"></select>
    </label>
</div>

这是控制器(模板的控制器是来自$ routeProvider的HomeCtrl)

angular.module('feedsmanagerApp').controller('HomeCtrl', function ($scope, $rootScope, $location, ngDialog, userService) {
    $scope.advertisers = [];
    userService.getUser().then(function(user) {
        $scope.$evalAsync(function() {
            $scope.advertisers = user.getAdvertisers();
        })
    });
//more stuff down here....

从user.getAdvertisers()返回的数据如下所示:

[{name:'aaaa', id:0}, {name:'bbbb', id:1}];

最后,这是userService

var userPromise,

        getUser = function() {
            if(!userPromise) {
                var deferred = $q.defer();
                userPromise = deferred.promise;
                deferred.resolve(User.createFromServerData(null));
            }
            return userPromise;
        };

我尝试过使用$ timeout,$ scope。$ apply,$ scope。$ evalAsync ...我几乎没有想法。我根本无法在选择中显示任何数据。任何帮助将非常感谢!感谢。

2 个答案:

答案 0 :(得分:0)

我认为这应该有效:

userService.getUser().then(function(user) {
    $scope.advertisers = user.getAdvertisers();
});

或者,如果getAdvertisers返回一个承诺:

userService.getUser().then(function(user) {
    user.getAdvertisers().then(function (advertisers) {
        $scope.advertisers = advertisers;
    });
});

答案 1 :(得分:-1)

没关系。这是我检索数据的方式的问题。 d&#39;!哦