ngOptions不作为添加到数组的对象更新

时间:2014-02-26 01:12:56

标签: javascript angularjs scope ng-options

我有一个包含对象的数组。当我将新对象推送到此列表时,视图不会更新以添加新对象。我认为它与$ scope有关。$ apply但我不知道如何使用它。我试过围绕这个包装推送功能,但工厂说$ scope是未定义的。

查看:

        <label for="groupOwner">List Template:
            <select 
                id="listTemplate"
                ng-model="newList.template"
                ng-options="t.name for t in listTemplates|orderBy: 'name'"
            ></select>
        </label>

控制:

    $scope.createList = function (){
        var modalForm = '/Style%20Library/projects/spDash/app/partials/newList.html';   
        var modalInstance = $modal.open({
            templateUrl: modalForm,
            backdrop: true,
            windowClass: 'modal',
            controller: 'newListCtrl',
            resolve: {
                newListData: function (){
                    return $scope.newList;
                }
            }
        });

        modalInstance.result.then(function(newList){
            SiteService.createList(newList,$scope.site);
        });
    };

服务功能:

var createList = function (newList, site){
    var promise = $().SPServices({
        operation: "AddList",
        webURL: site.url,
        listName: newList.name,
        description: newList.description,
        templateID: newList.template.id
    })

    promise.then(function (){
        addToQuickLaunch(newList.name,site.url)
        getSiteInfo(site);
        //take new list object and push to siteLists array
        siteLists.push(newList);
    },function (reason){
        console.log('Failed: ' + reason);
    })
}  

function addToQuickLaunch (name,siteUrl) {
    $().SPServices({
      operation: "UpdateList",
      webURL: siteUrl,
      listName: name,
      listProperties: "<List OnQuickLaunch='TRUE' EnableVersioning='TRUE'/>",
      completefunc: function(xData,Status){
        console.log(name + " list created")
      }
    });
}

1 个答案:

答案 0 :(得分:0)

此代码向我发出立即标志:

modalInstance.result.then(function(newList){
    SiteService.createList(newList,$scope.site);
});

您不应该通过这样的服务从控制器传递数组。相反,这样做:

modalInstance.result.then(function(newList){
    return SiteService.createList(newList);
}).then(function(list) {
  $scope.site.lists.push(list);
});

在这种情况下,您将createList返回一个承诺,并使用要添加到$scope.site.lists的对象解决该承诺。但是,您应该注意,控制器中不应该有这么多逻辑。通过使用一个返回promise并隐藏这些细节的方法来进一步抽象。您的控制器应该只有:

someService.someMethod().then(function(result) {
  $scope.whatever.push(result);
});