我研究AngularJS,现在尝试根据一个(或多个)条件添加属性。
但是这段代码( CodePen here )似乎无法运作:
function myController($scope) {
console.log("start");
$scope.item = { myBool: false };
$scope.myClick = function(e) {
var myHref = angular.element(e.delegateTarget).data(href);
console.log(myHref);
};
}
.test{background: lightblue; height: 50px; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div np-app ng-controller="myController">
<div class="test"
data-href="{undefined: !item.myBool, 'http://yes.com': item.myBool}"
ng-click="myClick($event);console.log('end');">click & see the console</div>
</div>
实际上{@ 1}}属性不应定义为data-href
...
答案 0 :(得分:3)
angular.module('myApp', [])
.controller('myController', function($scope) {
console.log("start");
$scope.item = {
myBool: false
};
$scope.myClick = function(e) {
$scope.item.myBool = !$scope.item.myBool;
console.log(angular.element(e.target).attr("href"));
};
});
&#13;
.test{background: lightblue; height: 50px; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<div class="test" href="{{item.myBool ? 'http://yes.com' : undefined}}" ng-click="myClick($event)">
click & see the console
</div>
</div>
&#13;
答案 1 :(得分:0)
最后,将Vanojx1的答案更新为:
angular.module('myApp', [])
.controller('myController', function($scope) {
console.log("start");
$scope.item = { myBool: false };
$scope.myClick = function(e) {
$scope.item.myBool = !$scope.item.myBool;
console.log(angular.element(e.target).attr("href"));
console.log(angular.element(e.target).attr("noarg"));
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<div class="test" ng-attr-href="{{item.myBool? 'http://yes.com' : undefined}}" ng-click="myClick($event)">
click & see the console
</div>
</div>
重要改进:
> 1.3
(实际上我使用的是古代版本); ng-attr-xxx
,则使用已移除的undefined
属性(属性本身,而不仅仅是其值);