我的控制器名称中有一个函数为 enableEditor ,如果我从直接HTML中调用函数,即(添加),它正在工作。但是,如果我为通过指令创建的元素调用函数,即(编辑)不起作用。如果有任何想法,请查看我的代码并建议我。
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Example - example-example53-production</title>
<script src="js/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div user-name=""></div>
<div>
<a href="#" ng-click="enableEditor()">add</a>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope','$filter', function ($scope,$filter) {
$scope.enableEditor = function() {
alert("123");
};
}]);
myApp.directive("userName", function() {
return {
restrict: "A",
scope: {
value: "=userName"
},
template: '<div class="click-to-edit">' +
'<a href="#" ng-click="enableEditor()">Edit</a>' +
'</div>'
};
});
</script>
</body>
</html>
答案 0 :(得分:2)
由于您有一个独立的范围,该函数属于指令的范围而不是您的控制器。尝试在指令范围内使用&
,如下所示:
<body ng-controller="MainCtrl">
<div user-name="" callme="enableEditor()"></div>
<div>
<a href="#" ng-click="enableEditor()">add</a>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope','$filter', function ($scope,$filter) {
$scope.enableEditor = function() {
alert("123");
};
}]);
myApp.directive("userName", function() {
return {
restrict: "A",
scope: {
value: "=userName",
callme:"&"
},
template: '<div class="click-to-edit">' +
'<a href="#" ng-click="callme()">Edit</a>' +
'</div>'
};
});
属性callme="enableEditor()"
用于将方法传递给scope指令,指令范围使用&
来表示方法callme:"&"
。另一个例子:
method2="someMethod()"
喜欢
scope: {
value: "=userName",
callme:"&",
method2:"&"
},template: '<div class="click-to-edit">' + '<a href="#" ng-click="callme()">Edit</a>' + '<a href="#" ng-click="Method2()">Save</a>' + '</div>'