如何在角度js中获取自定义属性的值

时间:2017-04-02 10:03:19

标签: javascript angularjs

我在角度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)

中获得了 undefined

完整代码......

<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>

3 个答案:

答案 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>