简体   繁体   中英

Changing $scope property and watching for changes

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 :

  • How (any possible way is welcome) could I programmatically have access to and change the documents array? (insert/remove/etc)
  • How can I set up an event which fires up when the array has been changed, eg an element has been inserted?

Accessing the array

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.

Detecting changes in the array

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.

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!
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM