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>
Angular code:
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
}
});
There will be a Show Directive Scope button in the page. When I click it, I want angular to find the DOM with id=aaa, then get and log it's scope created by directive myd1.
But it will print undefined, where is wrong?
Live demo: http://plnkr.co/edit/ravJoVH2oGLDD0VUsO82?p=preview
Answer without 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());
};
});
jqLite doesn't support selectors. Include jQuery before Angular in your plunker and it will work:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
You can also simplify your log a bit, since var aaa is a wrapped jQuery element:
console.log(aaa.scope());
Working plunker: http://plnkr.co/edit/bUsxo2UBWuiNkXBf8fsI?p=preview