AngularJS Custom Directive Two Way Binding

前端 未结 5 1076
甜味超标
甜味超标 2020-12-29 08:17

If I have an AngularJS directive without a template and I want it to set a property on the current scope, what is the best way to do it?

For example, a directive tha

5条回答
  •  死守一世寂寞
    2020-12-29 09:11

    I'm surprised no one has mentioned ng-model, the default directive for doing two-data binding. Maybe it's not so well known, but the linking function has a fourth parameter:

    angular.module('directive-binding', [])
      .directive('twoway', 
          function() {
            return {
              require: '?ngModel',
              link: function(scope, elem, attrs, ngModel) {
                elem.on('click', function() {
                  var counter = ngModel.$viewValue ? ngModel.$viewValue : 0
                  ngModel.$setViewValue(++counter);
                  scope.$apply();
                });
              }
            };
          }
        );
    

    On your view

    
    

    Click Count: {{ counter }}

    The fourth parameter is an API for the ngModelController, which has many uses for handling (parsing and formatting, for instance) and sharing data between a directive and a scope.

    Here's the updated Plunker.

提交回复
热议问题