AngularJS指令在元素具有绑定值的情况下不起作用
AngularJS directive not working where element have a binding value
我有一个指令来显示/隐藏基于某些内容的元素。但是当元素绑定到某个值时,它不起作用。我希望我的指令在这种情况下仍然有效。
angular.module("app", [])
.controller('ctrl', function ($scope){
$scope.color = "red";
})
.directive('xred', function() {
return {
link: function(scope, element, attrs) {
var role = 0;
if (role === 0) element.css('display', 'none');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<!-- where I hard code 'blue', xred directive is working-->
<span xred style="color: blue"> Blue (should hide) </span>
<!-- where I bind color, xred directive is not working.-->
<span xred style="color: {{color}}"> Red (should hide) </span>
</div>
不确定我是否理解您的问题,但使用ngStyle
它似乎有效:
angular.module("app", [])
.controller('ctrl', function ($scope){
$scope.color = "red";
})
.directive('xred', function() {
return {
link: function(scope, element, attrs) {
var role = 0;
if (role === 0) element.css('display', 'none');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<!-- where I hard code 'blue', xred directive is working-->
<span xred style="color: blue"> Blue (should hide) </span>
<!-- where I bind color, xred directive is not working.-->
<span xred ng-style="{color: color}"> Red (should hide) </span>
</div>
因为你使用 Angular 的插值设置了一个样式,所以它现在会跟踪它的属性值本身,你通过直接触摸元素所做的任何更改都将随时被 Angular 覆盖(比如设置 display: none
基本上只是修改style
属性,然后被 color: {{color}}
覆盖(。
因此,在您的情况下,尽量不要直接写入style
属性,而是使用ngStyle
或ngClass
。
我只在您的示例中添加了类 hidden
并添加/删除它以显示/隐藏您的元素。
angular.module("app", [])
.controller('ctrl', function ($scope){
$scope.color = "red";
})
.directive('xred', function() {
return {
link: function(scope, element, attrs) {
var role = 0;
if (role === 0) {
element.addClass('hidden');
}
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<style>
.hidden { display: none; }
</style>
<div ng-app="app" ng-controller="ctrl">
<!-- where I hard code 'blue', xred directive is working-->
<span xred style="color: blue"> Blue (should hide) </span>
<!-- where I bind color, xred directive is not working.-->
<span xred style="color: {{color}}"> Red (should hide) </span>
</div>
相关文章:
- 为什么jQuery悬停方法在这种情况下不起作用
- 为什么push方法没有'在这种情况下不起作用:[].推
- 倒计时在某些情况下不起作用
- res.download()在我的情况下不起作用
- 为什么getElementbyId在这种情况下不起作用
- $animate.removeClass 在没有 $evalAsync inside 指令的情况下不起作用
- 为什么 array.indexOf(undefined) 在数组稀疏的情况下不起作用
- 多次点击功能在不重新加载页面的情况下不起作用
- 数据绑定在特定情况下不起作用(AngularJS)
- UI 路由加载微调器在没有$timeout的情况下不起作用
- 为什么原型JavaScript在这种情况下不起作用
- ng-重复运行次数与整数参数一样多在某些情况下不起作用
- AngularJS指令在元素具有绑定值的情况下不起作用
- 为什么隐藏/显示(向上滑动/向下滑动)在这种情况下不起作用
- $('option').mousedown 事件在少数情况下不起作用
- Angular JS自定义指令在没有ng-app指令的情况下不起作用
- Django {{ block.super }} 在特定情况下不起作用
- Ajax 请求在没有警报语句的情况下不起作用
- 替换c#函数bijJquery在不知道如何进行故障排除的情况下不起作用
- clearInterval在特定情况下不起作用(javasripct,jquery)