Reputation: 22820
OK, I'm 1-day new to AngularJS, so this has to be ultra-basic (I hope not an ignorant one about how AngularJS works - I admit MVC is not really my thing, but anyway...).
My Code :
var PP = angular.module('PP', []);
PP.controller('documentController', function ($scope) {
$scope.documents = [
{
'filename': 'Untitled-1',
'content': 'Content-1'
},
{
'filename': 'Untitled-2',
'content': 'Content-2'
},
{
'filename': 'Untitled-3',
'content': 'Content-3'
},
];
});
So, I have declared a module (PP
), with a controller (documentController
) and a property(?) in it (documents
).
So, I have 2 questions :
documents
array? (insert/remove/etc)Upvotes: 0
Views: 98
Reputation: 13663
In your controller, you just use:
$scope.documents.push({filename: 'Another', content: 'Document'})
You can do that in any controller function because the array is a variable shared in the scope. Since it's in the scope, you can also access it in your view like so:
<button ng-click="documents.push({filename: 'Another', content: 'Document'})">
Add document
</button>
Usually, I'd define convenience functions for this behavior in the controller to be used in views, but in this simple example, this should do.
To watch changes in a collection, you can use $scope.$watchCollection
:
$scope.$watchCollection('documents', function(newDocuments, oldDocuments) {
// do something when the documents array changes
});
For a comparison between $watch
and $watchCollection
, see Scope $watch() vs. $watchCollection() In AngularJS.
Note that watches can be tricky: It's not always trivial to detect changes correctly, in my experience those functions are called way more often than they should.
Depending on your use-case, you might get by without any watches (Angular provides many ways to react on changes without using a single watch), and you probably shouldn't use $watch in your controllers anyway.
Upvotes: 3
Reputation: 6666
You access documents the same way you'd access any other javascript array. Meaning the usual operations are available.
This is how you listen for changes:
$scope.$watchCollection('documents', function(val){
// documents have changed!
});
Upvotes: 1