ngOptions 没有随着对象添加到数组而更新
-
21-12-2019 - |
题
我有一个包含对象的数组。当我将新对象推送到此列表时,视图不会更新以添加新对象。我认为它与 $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")
}
});
}
解决方案
这段代码向我抛出一个立即标志:
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);
});
不隶属于 StackOverflow