1

I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

<div ng-controller="myCon" test="abc"></div> then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

<div ng-controller="myCon"> <div test="def"></div> </div>

In this case I got undefined in alert($attrs.test)

Full code...

<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>
anoop
  • 3,812
  • 2
  • 16
  • 28
Scott Hunter
  • 231
  • 1
  • 3
  • 11

3 Answers3

3
app.directive("test", function() {
  return {
     restrict: "A",
        scope: {
            text: "@test"
        }
  };
});

Update your directive scope and add restrict . For better understanding refer to this question

Community
  • 1
  • 1
Abdullah Al Noman
  • 2,817
  • 4
  • 20
  • 35
0

You can check it:

<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>
anis programmer
  • 989
  • 1
  • 10
  • 25
0

You can get the element on click if you pass $event in ng-click, i.e. ng-click="check($event)" and can get the attribute from $event.target.

Check fiddle : 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>