I have an array which contains objects. When I push a new object to this list, the view does not update to add the new object. I assume it has to do with the $scope.$apply but I'm not sure how to use it. I've tried wrapping the push function around this but the factory says $scope is undefined.
View:
<label for="groupOwner">List Template:
<select
id="listTemplate"
ng-model="newList.template"
ng-options="t.name for t in listTemplates|orderBy: 'name'"
></select>
</label>
Ctrl:
$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);
});
};
Service function:
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")
}
});
}
This code throws an immediate flag to me:
modalInstance.result.then(function(newList){
SiteService.createList(newList,$scope.site);
});
You shouldn't pass the array from the controller through the service like that. Instead, do this:
modalInstance.result.then(function(newList){
return SiteService.createList(newList);
}).then(function(list) {
$scope.site.lists.push(list);
});
In this case, you'll have createList
return a promise, and resolve that promise with the object that is to be added to $scope.site.lists
. However, you should note that you should not have this much logic in your controller. Abstract this further by having a single method that returns a promise and hide these details. Your controller should simply have:
someService.someMethod().then(function(result) {
$scope.whatever.push(result);
});