在AngularJS的指令中绑定onChange事件

时间:2016-08-05 09:31:48

标签: angularjs

这是我期望它的样子的一个例子:

link: function (scope, element, attribute) {                
    // and these value we get inside link function
    // Listen for change events to enable binding
    // element.on('change', function () {
        //functionality here...
    // });
}

3 个答案:

答案 0 :(得分:0)

function listener() {
  return {
   link: function(scope, elem, attrs) {
     elem.bind("change", function() {
       alert('change');
     });
   }
  }
}

angular.module('myApp', []);
angular
  .module('myApp')
  .directive('listener', listener);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
    <select listener><option>1</option><option>2</option></select>
</div>

答案 1 :(得分:0)

这里是angular js

中事件绑定的示例指令代码
var myApp=angular.module('testApp',[]);
myApp.directive('clickme', function() {
  return function(scope, element, attrs) {
    var clickedCallback = function() {
      alert('Hello World!')
    };
    element.bind('click', clickedCallback);
  }
});

答案 2 :(得分:0)

你可以达到你想要的效果,几乎与你期望的一样:

&#13;
&#13;
angular.module('app', []);
angular
  .module('app')
  .directive('myDirective', myDirective);

function myDirective() {
  return {
    link: function (scope, element, attributes) {
      element.bind('change', callback);

      function callback() {
        alert('change');

        // do some stuff here
      }
    }
  };
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<div ng-app="app">
    <input type="text" my-directive />
</div>
&#13;
&#13;
&#13;

注意

更重要的是,如果它应该使用scope进行一些操作,则应使用scope.$apply,因为您正在处理不受Angular JS生活影响的DOM事件周期。在这种情况下,callback应如下所示:

function callback() {
    scope.$apply(function () {
        // do some manipulations with `scope`here
    });
}