【发布时间】:2017-01-08 13:58:00
【问题描述】:
我在一页中使用了两次指令。在指令中,我放置了一个按钮,单击该按钮会删除第一个指令并显示另一个。但是即使触发 ng-click 函数,这些值也不会改变。我究竟做错了什么?这是我的 HTML 代码。
<body ng-controller="mainCtrl">
<new-directive ng-show="firstDirective" passvar="first passing value"></new-directive>
<new-directive ng-show="secondDirective" passvar="second passing value"></new-directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
test.html 文件:
{{content}}, {{passvar}} <button ng-click="otherOne()">show other directive</button>
JS文件:
app.controller('mainCtrl', function($scope){
$scope.firstDirective = true;
});
app.directive('newDirective',function(){
// Runs during compile
return {
restrict: 'E',
templateUrl: 'test.html',
scope: {
passvar: '@'
},
controller: function ($scope) {
$scope.content= 'Random Content';
$scope.firstDirective = true;
$scope.firstDirective = false;
$scope.otherOne = function(){
$scope.firstDirective = false;
$scope.secondDirective = true;
}
}
};
});
即使显示第一个指令,我也必须添加 $scope.firstDirective = true;在主控制器中,而不是在指令的控制器中。
【问题讨论】:
-
指令中的作用域只是引用指令的作用域,你可能需要使用 $rootscope 或 $scope.$parent 来改变主控制器的变量。
-
为什么需要某个指令来隐藏/显示另一个指令?如果你有两个以上怎么办?为什么不能让控制器决定应该显示什么指令?
-
因为不会超过 2 个。它们会比我在这里列出的更复杂。我刚刚在这里添加了一个简单的,以了解我做错了什么。
标签: javascript html angularjs angular2-directives