Watch controller model value from inside directive

前端 未结 4 399
天命终不由人
天命终不由人 2020-12-13 04:57

I am trying to have angular watch the $viewValue of a controller from inside a directive.

fiddle: http://jsfiddle.net/dkrotts/TfTr5/5/

f         


        
相关标签:
4条回答
  • 2020-12-13 05:33

    If you want debounce on a model value, it is worth mentioning the debounce setting in ng-model-option:

    <input type="text" ng-model-options="{ debounce: 1000 }" ng-model="search"/>
    

    For example: this watch is trigger 1000 ms after change and reset at new changes.

    scope.$watch(attrs.ngModel, function(newValue) { });
    

    https://docs.angularjs.org/api/ng/directive/ngModelOptions

    0 讨论(0)
  • 2020-12-13 05:36

    If you want to bind a value inside isolated scope,there are 2 ways to do it.The first way you can use even you don't have isolated scope.Here are the ways:

    1) use $attrs.any_attribute and bind it (set in watch)

    2) use 2 ways binding ('=') method and set it into listener

    if you want more with examples here is a great article

    http://www.w3docs.com/snippets/angularjs/bind-variable-inside-angularjs-directive-isolated-scope.html

    0 讨论(0)
  • 2020-12-13 05:41

    Wanted to add: in 1.2.x, with isolated scope, the above wont work. http://jsfiddle.net/TfTr5/23/

    A workaround I came up with was using the fact that $watch also accepts a function, so you can access your controller using that.

    scope.$watch(
        function(){return controller.$viewValue},
        function(newVal, oldVal){
            //code
        }
    )
    

    Working fiddle: http://jsfiddle.net/TfTr5/24/

    If anyone has an alternative, I would gladly welcome it!

    0 讨论(0)
  • 2020-12-13 05:44

    $watch accepts the "name" of the property to watch in the scope, you're asking it to watch the value. Change it to watch attrs.ngModel which returns "bar", now you're watching scope.bar. You can get the value the same way you were or use scope[attrs.ngModel] which is like saying scope["bar"] which again, is the same as scope.bar.

    scope.$watch(attrs.ngModel, function(newValue) {
        console.log("Changed to " + newValue);
    });
    

    To clarify user271996's comment: scope.$eval is used because you may pass object notation into the ng-model attribute. i.e. ng-model="someObj.someProperty" which won't work because scope["someObj.someProperty"] is not valid. scope.$eval is used to evaluate that string into an actual object so that scope["someObj.someProperty"] becomes scope.someObj.someProperty.

    0 讨论(0)
提交回复
热议问题