按钮在angularjs指令中不起作用
Button inside angularjs directive does not work
我在一个页面中使用了两次指令。在指令内部,我放置了一个按钮,点击删除第一个指令并显示另一个。但即使在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;
}
}
};
});
即使是为了显示第一个指令,我也必须添加$作用域。firstDirective = true;在主控制器中,而不是在指令的控制器中
这是因为你的指令的作用域是隔离的,$scope.firstDirective
和$scope.secondDirective
在指令的父作用域上。
简单的答案是使用$scope.$parent.firstDirective
和$scope.$parent.secondDirective
。
我个人会这样设置:
app.controller('mainCtrl', function($scope){
$scope.show = {
'firstDirective': true,
'secondDirective': false
};
});
app.directive('newDirective',function(){
// Runs during compile
return {
restrict: 'E',
templateUrl: 'test.html',
scope: {
passvar: '@',
show: '=showDirectives',
shows: '@',
hides: '@'
},
controller: function ($scope) {
$scope.content= 'Random Content';
$scope.otherOne = function(){
$scope.show[$scope.hides] = false;
$scope.show[$scope.shows] = true;
}
}
};
});
和模板
<body ng-controller="mainCtrl">
<new-directive ng-show="show.firstDirective" show-directives="show" shows="secondDirective" hides="firstDirective" passvar="first passing value"></new-directive>
<new-directive ng-show="show.secondDirective" show-directives="show" shows="firstDirective" hides="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>
相关文章:
- Angular指令在alertify setContent内容中不起作用
- AngularJS指令部分应用的函数don'不起作用
- Google Maps API OverlayView()在AngularJS指令中不起作用
- mouseover和mouseleave文本颜色更改在指令链接中不起作用
- 这段jquery代码在angular指令中不起作用
- Angular Filter在指令表达式中不起作用
- Angular UI Select2指令搜索功能不起作用
- 新的自定义角度指令不起作用
- 对于使用传递的数据计算的局部范围变量,角度绑定在自定义指令中不起作用
- 滚动指令在Angular JS中不起作用
- 角度指令双向绑定不起作用
- Angular.JS自定义指令;不起作用
- 指令中选择输入的双向绑定不起作用
- ng中使用的指令包括dond'不起作用
- scope.$apply 是未定义的,在 scrolly 指令中不起作用
- AngularJS,自定义指令不起作用@ plnkr
- 指令的角度优先级不起作用
- Angular js指令使用控制器作为语法ng点击不起作用
- 指令链接中的绑定不起作用
- ng 路由不起作用指令