我看到很多問題,其中有人問如何在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()
方法得到的元素。