Feeling a bit lost with 2-way data binding in Angular. Take a look at this code snippet!
the var bah
can access the parent object $scope.something
, but when I click the button, the value in the controller changes to false
while it remains unchanged in the directive. What could be causing this? Is it a bug?
Any suggestions on how to solve this issue would be greatly appreciated. If possible, could you provide an example or reference links?
HTML
<div ng-controller="myController">
show me something {{ something }} <br>
<button ng-click="toggleSomething"><button>
<!-- this is a canvas -->
<my-directive></my-directive>
</div>
JS
angular.module('fooBar',[]).controller('myController', ['$scope', function($scope) {
// this is the something
$scope.something = true;
$scope.toggleSomething = function(){
if($scope.something) {
$scope.something = false
} else {
$scope.something = true
}
}
}]).directive('myDirective', function(){
return {
template: '<canvas width="500px" height="500px"></canvas>',
link: function(scope, el, attr) {
//how to access that 'something'
var bah = scope.$parent.something;
}
};
});
UPDATE Huge thanks to everyone, especially to @immirza for the assistance!
I apologize for not being able to respond individually.
The solution was simply adding $parent
.
//how to access that 'something'
var bah = scope.$parent.something