2016-08-05 45 views
-1

這是一個僞指令中綁定onChange事件是如何,我希望它看起來像一個例子:的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... 
    // }); 
} 

回答

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>

+0

來到同樣的事情..「改變」事件不會被解僱時價值變化角度結合的結果 –

0

這裏是在事件綁定的例子指令代碼角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); 
    } 
}); 
0

你可以實現你想要做的事alm OST同你期望:

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 
 
     } 
 
    } 
 
    }; 
 
}
<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>

注意

更過來,如果它應該做一些操作與scope然後scope.$apply應該使用,因爲你處理DOM超出Angular JS生命週期的事件。在這種情況下,callback應該是這樣的:

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