【发布时间】:2015-04-27 19:18:38
【问题描述】:
我是 AngularJS 的新手,正在尝试创建我的第一个自定义指令。
实际上,我创建了两个指令,每个指令都使用它自己的控制器。也许我弄错了,但我希望每个指令控制器都使用它自己的隔离 $scope。但在“指令一”的模板中,我可以从“指令二”调用变量,反之亦然。
如何为每个指令获得一个独立的 $scope,以便每个指令的模板只能使用它自己的变量?
index.html:
<!DOCTYPE html>
<html ng-app="application">
<head>
<script src="https://code.angularjs.org/1.2.28/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Testing Custom Directives</h1>
<hr />
<directive-one></directive-one>
<directive-two></directive-two>
</body>
</html>
script.js:
var app = angular.module('application', [ ]);
app.directive('directiveOne', function(){
return {
restrict: 'E',
template: '<h3>Directive 1</h3> {{dirCtrlOne.name}} {{dirCtrlTwo.year}}',
controller:function(){
this.name = 'John';
},
controllerAs: 'dirCtrlOne'
}
});
app.directive('directiveTwo', function(){
return {
restrict: 'E',
template: '<h3>Directive 2</h3> {{dirCtrlTwo.year}} {{dirCtrlOne.name}}',
controller:function(){
this.year = 1990;
},
controllerAs: 'dirCtrlTwo'
}
});
【问题讨论】:
标签: javascript angularjs