Angularjs: 'controller as syntax' and $watch

前端 未结 10 1525
抹茶落季
抹茶落季 2020-11-28 18:52

How to subscribe on property change when using controller as syntax?

controller(\'TestCtrl\', function ($         


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 19:58

    Here is how you do this without $scope (and $watch!) Top 5 Mistakes - Abusing watch

    If you are using "controller as" syntax, it's better and cleaner to avoid using $scope.

    Here is my code in JSFiddle. (I am using a service to hold the name, otherwise the ES5 Object.defineProperty's set and get methods cause infinite calls.

    var app = angular.module('my-module', []);
    
    app.factory('testService', function() {
        var name = 'Max';
    
        var getName = function() {
            return name;
        }
    
        var setName = function(val) {
            name = val;
        }
    
        return {getName:getName, setName:setName};
    });
    
    app.controller('TestCtrl', function (testService) {
        var vm = this;
    
        vm.changeName = function () {
            vm.name = new Date();
        }
    
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: false,
            get: function() {
                return testService.getName();
            },
            set: function (val) {
                testService.setName(val);
                console.log(vm.name);
            }
        }); 
    });
    

提交回复
热议问题