Trying to grasp the concept of Angular JS directives has left me feeling confused about the scopes and relationship between the parent controller and directives. Specifically:
1) I added the "hello-world" directive (which has its own controller, see code below) into the "myCtrl", essentially as a child.
2) In the directive, there is a variable called "directiveVar" and in the controller, there is another variable called "controllerVar", each with different values.
3) My confusion arises from the following:
- Since myCtrl is the parent of the "hello-world" directive, the directive should be able to inherit variables from the controller by default.
- However, I noticed that the child "hello-world" directive variables can also be seen in the parent, myCtrl.
- This raises the question of how it is possible for the child to inherit parent values but then have the parent inherit child values?
- I am also curious about the purpose of the controller in the directive (although I understand the reason behind it, I feel a bit confused and would appreciate some clarification if I'm missing something).
var myapp = angular.module('myapp', []);
angular.module('myapp').directive('helloWorld', function() {
return {
restrict: 'AE',
replace: true,
template: '<p style="background-color:{{color}}">Hello World<br /> <br />{{color}} <br /> <br /> {{directiveVar}}',
controller: function ($scope) {
$scope.color = '#0080ff';
$scope.directiveVar = "I am directive varible";
},
link: function(scope, elem, attrs) {
elem.bind('click', function() {
elem.css('background-color', 'white');
console.dir(scope);
scope.$apply(function() {
scope.color = "white";
});
});
elem.bind('mouseover', function() {
elem.css('cursor', 'pointer');
});
}
};
});
angular.module('myapp').controller('myCtrl', function($scope) {
$scope.color = '#ffb399';
$scope.controllerVar = "I am controller varible";
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>AngularJS: UI-Router Quick Start</title>
<!-- Bootstrap CSS -->
<link href="lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
</head>
<body ng-controller="myCtrl">
<input type="text" ng-model="color" placeholder="Enter a color" />
<br />
<br />
{{color}}
<br />
<br />
{{directiveVar}}
<br /> <br />
<hello-world/>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular-animate/angular-animate.js"></script>
<script src="lib/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="lib/angular-bootstrap-contextmenu/contextMenu.js"></script>
<script src="lib/angular-sanitize/angular-sanitize.js"></script>
<script src="lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="app.js"></script>
</body>
</html>