[英]What is the proper way to extend the behavior of a custom Angular directive?
[英]Proper “Angular” way to pass behavior to directive?
在查找有关Angular指令和将行为传递给指令的信息时,我最终被指向隔离范围上的方法绑定方向,即
scope: {
something: '&'
}
这个功能的文档有点混乱,我不认为它最终会做我想要的。
我最终提出了这个片段(简化为简洁),它通过在HomeCtrl
传递一个范围函数来HomeCtrl
,并且该指令完成它的工作并调用该函数。 (只是重要的是,真正的代码会传回指令的承诺)。
angular.module('app', []); angular.module('app') .directive('passingFunction', function() { var changeFn, bump = function() { console.log('bump() called'); internalValue++; (changeFn || Function.prototype)(internalValue); }, internalValue = 42; return { template: '<button ng-click="bump()">Click me!</button>', scope: { onChange: '<' }, link: function(scope, element, attrs) { if (angular.isFunction(scope.onChange)) { changeFn = scope.onChange; } scope.bump = bump; } }; }) .controller('HomeCtrl', function($scope) { $scope.receive = function(value) { console.log('receive() called'); $scope.receivedData = value; }; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.4/angular.min.js"></script> <div ng-app="app" ng-controller="HomeCtrl"> <passing-function on-change="receive"></passing-function> <p>Data from directive: {{receivedData}}</p> </div>
这是实现这一目标的正确“角度”方式吗? 这似乎有效。
您需要的是将函数传递给指令。 我会做一个很小的例子。
在控制器上:
$scope.thisFn = thisFn(data) { console.log(data); };
在html中:
<my-directive passed-fn="thisFn()"></my-directive>
指令:
.directive('myDirective', [
() => {
return {
restrict: 'E',
scope: {
passFn: '&'
},
template: '<div id="myDiv" ng-click="passFn(data)"></div>',
link: (scope) => {
scope.data = "test";
}
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.