AngularJS: view variables without $ watch

I recently discovered that Javascript is " Call by sharing " (Wikipedia explanation), which means that, in fact, everything is passed by value, however the original contents of the object can still be changed. Quick example:

function changeObjectProperties(obj) {
    obj.p = 20;
}

var obj = { p: 10; }
changeObjectProperties(obj);
console.log(obj.p); // will print 20; it changed!

This made me wonder if this could be used in Angular to view variables without using $ scope. $ watch. The following work.

controllers.js:

.controller('Listener', function($scope, UserService) {
    $scope.user = UserService.getUser();
})

.controller('Changer', function($scope, UserService) {

    // let imagine the UI has some button that changes the e-mailadres
    $scope.buttonClick = function() {
        UserService.setEmail('foo@bar.com');
    }
});

services.js:

.factory('UserService', function() {
    var user = {
        name: 'Foo',
        email: 'example@example.com'
    };

    return {
        getUser: function() { return user; }
        setEmail: function(email) { user.email = email; }
    };
});

The variable $scope.userin the controller is Listenerupdated when the user clicks a button in the controller Changer. This change shows whether this variable will be displayed in HTML.

, , , Listener .

, , , . , , , . , ? - , ?

+4
1

, . , , , Angular . , , - Angular, , , . . , , , .

, JavaScript- , Angular , .

, , , , , AngularJS, $watch: http://csharperimage.jeremylikness.com/2014/11/the-top-5-mistakes-angularjs-developers_28.html

0

All Articles