我无法理解如何定义具有隔离范围的指令(或内部)使用的函数。在以下代码中,为什么$scope.foo()
函数不执行?我有没有正确的方法来解决这个问题?我正在寻找一个只有在用户登录时才可见的按钮,并且认为指令是封装/隔离该功能的好方法。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.4.2/angular.js"></script>
<script>
angular.module('MyApp', [])
.directive('myScopedDirective', function() {
return {
scope: {}, // <!-- isolate scope breaks things
controller: function($scope) {
// isolate scope prevents this function from being executed
$scope.foo = function() {
alert('myScopedDirective / foo()');
};
}
};
});
</script>
</head>
<body>
<div ng-app="MyApp">
<!-- button doesn't work unless isolate scope is removed -->
<button my-scoped-directive ng-click="foo()">directive container - foo()</button>
</div>
</body>
</html>
答案 0 :(得分:4)
它无效,因为您在不同的范围ngClick
和myScopedDirective
使用了2个指令。您需要为您的指令创建一个模板并调用click函数,如下所示:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.4.2/angular.js"></script>
<script>
angular.module('MyApp', [])
.directive('myScopedDirective', function() {
return {
restrict: 'AE', // Can be defined as element or attribute
scope: {},
// Call the click function from your directive template
template: '<button ng-click="foo()">directive container - foo()</button>',
controller: function($scope) {
$scope.foo = function() {
alert('myDirective / foo()');
};
}
};
});
</script>
</head>
<body>
<div ng-app="MyApp">
<my-scoped-directive></my-scoped-directive>
</div>
</body>
</html>
工作plunker