HTML code:
<body ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
<div id="aaa" myd1>
In a directive
</div>
<button ng-click="showDirectiveScope()">Show Directive Scope</button>
</body>
角度代码:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope,$element) {
$scope.name = 'World';
$scope.showDirectiveScope = function() {
var aaa = $element.find("#aaa");
console.log(aaa);
console.log(angular.element(aaa).scope());
}
});
app.directive('myd1', function(){
return {
scope: true
}
});
页面中会出现显示指令范围按钮。当我点击它时,我希望angular找到带有id=aaa
的DOM,然后获取并记录它由指令myd1
创建的范围。
但它会打印undefined
,哪里出错了?
答案 0 :(得分:5)
没有jQuery的答案:
app.controller('MainCtrl', function($scope,$element,$window) {
$scope.name = 'World';
$scope.showDirectiveScope = function() {
var aaa = $window.document.getElementById('aaa');
console.log(aaa);
console.log(angular.element(aaa).scope());
console.log($element.scope());
};
});
答案 1 :(得分:1)
jqLite不支持选择器。在您的plunker中包含Angular之前的jQuery,它将起作用:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
您还可以稍微简化日志,因为var aaa
是一个包装的jQuery元素:
console.log(aaa.scope());