2017-04-02 67 views
1

我已经在角度js中创建了一个名为test的自定义属性。当我在ng-controller关键字i.d旁边写test属性时。如何在角度js中获取自定义属性的值

<div ng-controller="myCon" test="abc"></div>然后我可以通过使用alert($attrs.test)从控制器访问test。但是,如果我编写除ng-controller关键字旁边的自定义属性test,我无法访问它。即

<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

该属性将只能访问到测试指令的控制器 – ayushgp

+0

按钮在div哪里ng控制器写入。所以我认为按钮在该控制器下 –

+0

按钮在该控制器中,但该指令的属性不是。为了让父母能够访问它,你需要让父母访问其子范围。阅读关于它[这里](https://github.com/angular/angular.js/wiki/Understanding-Scopes) – ayushgp

回答

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> 
3
app.directive("test", function() { 
    return { 
    restrict: "A", 
     scope: { 
      text: "@test" 
     } 
    }; 
}); 

更新您的指令范围并添加限制。为了更好地理解是指this question

0

,如果你在传递$事件你可以在点击元素NG点击,即NG-点击=“检查($事件)”,并可以从$事件属性。目标

检查小提琴: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> 
相关问题