gpt4 book ai didi

javascript - Angular Directive(指令)隔离范围 : scope function won't execute

转载 作者:行者123 更新时间:2023-11-28 15:21:18 24 4
gpt4 key购买 nike

我无法理解如何定义具有隔离范围的指令(或内部)使用的函数。在下面的代码中,为什么$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>

骗子:http://plnkr.co/edit/Sm81SzfdlTrziTismOg6

最佳答案

它不起作用,因为您在不同的范围内使用了 2 个指令:ngClickmyScopedDirective。您需要为指令创建一个模板并调用 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

关于javascript - Angular Directive(指令)隔离范围 : scope function won't execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com