I am a newbie to AngularJS and while learning it I came across a wonderful post about how scopes are nested and inherited in HTML markup: Understanding Scopes
Also I went through this Plunker to understand what the above post is saying.
I have created this JSFiddle to understand the above concepts.
HTML:
<body ng-app="myApp">
<h1>Hello AngularJS!</h1>
<div ng-controller="myCtrl">{{hello}}
<div anchor-link>
<a href="javascript:;">click me</a>
<div ng-show="t.show">show me</div>
<div ng-hide="t.show">hide me</div>
</div>
</div>
</body>
JS:
var app = angular.module("myApp", []);
app.controller('myCtrl', function ($scope) {
$scope.hello = 'Hello World!';
$scope.t = {
show: true
};
});
app.directive('anchorLink', function () {
return {
restrict: 'EA',
link: function (scope, elem, attr) {
elem.on('click', function () {
scope.t.show = !scope.t.show;
});
}
};
});
Now my question:
Why doesn't two-way data binding work in my fiddle? Isn't the scope from my custom directive supposed to inherit from its parent (i.e. controller)?
If I am using
$scope.tas an object on controller scope. then why doesn't it toggle "show me" and "hide me" divs? I also tried usingscope: truein my custom directive, but it still doesn't work.Is it because
scopein my link function doesn't inherit prototypically?Is it really changing parent scope's
$scope.tobject?