指令如何从带有一些参数的控制器调用函数?
我会将变量 myVar 赋予范围。$apply(attrs.whattodo);
HTML:
<div ng-app="component">
<div ng-controller="ctrl">
<span ng-repeat="i in myarray">
<span customattr whattodo="addVal">{{i}}</span>
</span>
</div>
控制器 JS:
function ctrl($scope) {
$scope.myarray = [1];
$scope.addVal = function (value) {
$scope.myarray.push(value);
}
}
指令 JS:
angular.module('component', []).directive('customattr', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var myVar = 5;
scope.$apply(attrs.whattodo);
}
};
});