Getter & setter support with ng-model in AngularJs

后端 未结 2 1349
遥遥无期
遥遥无期 2021-02-20 02:52

I am trying to get getter/setter support for ng-model by implementing a directive that will take care of getting and setting the values to/from the view/model. I am almost there

2条回答
  •  再見小時候
    2021-02-20 03:24

    I think the question about breaking the digest loop has been answered. Here is a different, much cleaner approach to the same problem that doesn't involve $watch.

    When you don't need to support legacy browsers, use ECMAScript 5 accessors.

    Just add a property to your angular controller:

    Object.defineProperty(
        $scope, 
        "accessorWrappedMyValue",            
        {
            get : function() { return $scope.myValue; },  
            set : function(newValue) { 
                      $scope.myValue = newValue; 
                      $scope.myDerivedValue = $scope.myValue * 2;
                  },
            configurable: true
        });
    

    Now all you need to do is reference accessorWrappedMyValue from ng-model like so:

    
    

    Further reading

    This blog has a nice introduction to ES5 accessors.

    Use this feature matrix to decide whether you can go with ES5 or not. The interesting lines are "Getter / Setter in property initializer" and "Object.defineProperty".

提交回复
热议问题