gpt4 book ai didi

javascript - AngularJS 指令在元素具有绑定(bind)值的地方不起作用

转载 作者:行者123 更新时间:2023-11-30 16:16:43 25 4
gpt4 key购买 nike

我有一个指令来显示/隐藏基于某物的元素。但它在元素绑定(bind)到某个值的情况下不起作用。我希望我的指令在这种情况下仍然有效。

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>

关于javascript - AngularJS 指令在元素具有绑定(bind)值的地方不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35390551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com