问题描述:

I am beginning to learn Angularjs.

I have been successful in getting the data and assign it to model.

coreService.getCompanies().success(function(data) {

$scope.companies = data.companies;

});

However, I am not clear, how to update the model when I, insert or delete the entity.

categoryService.bulkDeleteCategories(companyId, selectedCategories).success(function(data) {

console.log('success category deletion');

$modalInstance.close('Success');

}).error(function(data, status) {

console.log('There was an error deleting categories' + data);

});

In the above snippet, I am inserting an entity through a dialog box. The request returns 200 OK. But how do I go about updating the model now? I have been providing a refresh link which refetches the data from server and updates the model, but I am sure there must be better way.

网友答案:

QUERY (getting all items)

Replace the scope model with your returned data, exactly as you did. ($scope.companies with data.companies)

INSERT

In your success handler, add the uploaded object locally to your model via push. That way, your model on the site gets only updated when the database got updated (aka the request was successful)

DELETE

In your success handler, delete the object also from your local model via splice(index, 1). Again, your model on the site gets only updated when the database deleted the item (aka the request was successful)

网友答案:

You have not provided enough code to provide a complete answer, but add something like the following to your success function

$scope.companies[companyID].categories = selectedCategories

In other words $scope is your model and you just adjust as you would any other variable. Once you update the model, and assuming you used $http in the service, then your onscreen data will refresh accurately.

相关阅读:
Top