为什么我不能在AngularJS中使用ng-show inside指令
Why i cannot use ng-show inside directive in AngularJS?
我试图使一个元素,显示它的内容时,点击它:有很多方法可以做到这一点。我想在指令内做。为什么不工作?
http://plnkr.co/edit/Y13bcD7Ikuk6pERM9Mm8?p =
预览HTML:<ez-option title="option 1">
Option 1 inside
<input ng-model="x">{{x}}
</ez-option>
<ez-option title="option 2">
Option 2 inside
</ez-option>
JavaScript: directive('ezOption',function(){
return {
template:'<li></li><div ng-show=selected ng-transclude class=body></div>',
link:function ($scope,iElement,iAttrs,controller,tanscludeFn){
iElement.find('li').html(iAttrs.title)
iElement.find('li').on('click',function(){
$scope.selected=true
})
},
scope:true,
transclude:true
}
})
这是因为angular没有意识到点击事件的作用域变化。要让它知道,你应该这样做
iElement.find('li').on('click',function(){
$scope.$apply(function() {
$scope.selected=true;
})
})
或者,你可以使用angular的ng-click
来代替
m.directive('ezOption',function(){
return {
template:'<li ng-click="selected=true"></li><div ng-show=selected ng-transclude class=body></div>',
link:function ($scope,iElement,iAttrs,controller,tanscludeFn){
iElement.find('li').html(iAttrs.title);
},
controller:function($scope){
$scope.selected=false
},
transclude:true
}
})
既然你的事件在angular之外…这是一个DOM事件,你需要告诉angular作用域的变化,这样它才能运行摘要。
使用$scope.$apply()
。如果你使用像ng-click
这样的核心事件指令,这是由angular在内部完成的。
iElement.find('li').on('click',function(){
$scope.selected=true;
$scope.$apply();
});
因此,在使用你自己的
之前,你通常最好使用大量的核心angular事件指令。相关文章:
- 使用angularjs ng Show/ng hide显示和隐藏不同的内容
- 我需要NG-IF/NG-SWITCH还是NG-SHOW&NG-HIDE
- 如何在AngularJS视图中使用promise(ng-show)
- AngularJS:如何使用java脚本函数更改跨度的ng-show条件
- ng show和ng hide don'I don’我一秒钟都不工作
- AngularJS:使用ng-show/hide动态维护下拉列表的3种状态(InProgress、Success、Err
- ng-show内容在页面加载过程中闪烁,尽管它不是真实的,并且ng-cloak不适用于FF
- 如何验证使用 ng-repeat、ng-show(角度)动态创建的输入
- 如何使用ng-repeat与清单模型进行ng-show
- AngularJS:ng-show不适用于ng-app
- 为什么我的html节点保持类ng隐藏属性ng show=true
- AngularJS:为什么ng show没有在IE11上运行
- Angularjs ng-show not working with checkbox with default val
- Angularjs - grouping ng show
- AngularJS:隐藏<td>使用ng-hide/ng-show没有间隙
- Angularjs ng-show == Id?
- 基于参数(angular)调用特定元素上的ng show
- 只有当我导航回窗口时,angular ng show才有效
- 使ng-show/ng-hide与由Angular之外的外部源修改的localStorage一起工作
- 为什么我不能在AngularJS中使用ng-show inside指令