我在角度js中创建了一个名为test
的自定义属性。当我在ng-controller关键字i.d旁边写test
属性时。
<div ng-controller="myCon" test="abc"></div>
然后我可以使用test
从控制器访问alert($attrs.test)
。但是,如果我编写自定义属性test
而不是ng-controller关键字,我就无法访问它。即
<div ng-controller="myCon">
<div test="def"></div>
</div>
在这种情况下,我在alert($attrs.test)
完整代码......
<html>
<script src="angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
alert(JSON.stringify($attrs.test)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>
答案 0 :(得分:3)
app.directive("test", function() {
return {
restrict: "A",
scope: {
text: "@test"
}
};
});
更新指令范围并添加restrict。为了更好地理解,请参阅this question
答案 1 :(得分:0)
您可以查看:
<html>
<script src="src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js""></script>
<body ng-app="myApp">
<div ng-controller="kumar" >
<button ng-click="check()" test="def">Click</button>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
//template : "<h1>Hello</h1>"
};
});
app.controller("kumar",function($scope,$attrs){
$scope.check=function(){
var testa=$scope.test;
alert(JSON.stringify(testa)); //getting undefined. I
//should get def.
}
});
</script>
</body>
</html>
答案 2 :(得分:0)
如果您在ng-click中传递 $ event ,即ng-click =“check($ event)”并且可以从 $ event获取属性,则可以点击该元素.TARGET 强>
检查小提琴:https://jsfiddle.net/ayusharma/xb63g9ca/
<强> JS 强>
app.controller('myCtrl', function($scope) {
$scope.clickMe = function(evt) {
console.log(evt.target.getAttribute('test'))
}
});
<强> HTML 强>
<div ng-controller="myCtrl">
<div ng-click="clickMe($event)" test="abc">Click on Me</div>
</div>