我看到很多问题,其中有人问如何在Angular中添加属性,但所有答案都使用ng-attr
解决方案,据我所知只设置值为的属性。如果条件不符合,我不希望我的属性出现。如何在Angular中有条件地添加属性(非属性值)
我该怎么做?
我看到很多问题,其中有人问如何在Angular中添加属性,但所有答案都使用ng-attr
解决方案,据我所知只设置值为的属性。如果条件不符合,我不希望我的属性出现。如何在Angular中有条件地添加属性(非属性值)
我该怎么做?
JQuery's attr()
method允许您设置属性名称和值。
在w3Schools有一个example of setting an attribute on click,它可以很容易地适用于自定义指令中的其他事件/条件。
更新...
的有条件地将所述disabled
属性到input
(文本框),如果它包含单词是长度大于8个字符Here is a somewhat trivial example。
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.words = ["Floral", "Curious", "Blunder", "Molecular", "Complicated",
"Drops", "Bumper", "Promise", "Clean", "Doubtless" ];
});
app.directive('disableLongWords', function($timeout) {
return {
restrict: "E",
link: function(scope, iElem, iAttrs) {
console.log(scope.word);
if (scope.word.length > 8) {
iElem.children().attr("disabled", "disabled");
}
}
}
});
HTML:
<body ng-controller="MainCtrl">
<disable-long-words ng-repeat="word in words">
<input type=text ng-model="word">
<br>
</disable-long-words>
</body>
根据什么属性你想要设置和在什么条件下,这可能是没有用的,在所有的发生,但是这是当我提出原始建议时,我正在考虑的一些事情。
可以使用 angular.element(element);
https://docs.angularjs.org/api/ng/function/angular.element
这之后您可以使用 .attr()
方法得到的元素。