Getter & setter support with ng-model in AngularJs

こ雲淡風輕ζ 提交于 2019-12-04 01:28:26

NOTE AngularJs 1.3 now supports Getter/Setter for ng-model. Refer to http://docs.angularjs.org/api/ng/directive/ngModelOptions for more information.


I could break the infinite loop with extra calls to

ngModelCtrl.$setViewValue()

and

ngModelCtrl.$render()

in the event handlers. Not sure if it's the best way to do it though.

See fiddle: http://jsfiddle.net/BDyAs/12/

EDIT:

I improved the code even more in

http://jsfiddle.net/BDyAs/15/

by separating the directive in separate ones for the getter and the setter.

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:

<input type="text" ng-model="accessorWrappedMyValue" />

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!