I am trying to understand the Angualr JS directives. But i am confused with the scopes and relation ship between the parent controller and directives. For example:
1) I inserted the "hello-world" directive (it has its own controller, please check below code) into the "myCtrl", i mean as a child.
2) I have one variable in the directive, "directiveVar" and other variable in the controller, "controllerVar", each has different values.
3) My confusion are as follows:
- As the myCtrl is the parent of the "hello-world" directive, so by default, "hello-world" directive scope can inherit the variables from the controller
- But i can see the child "hello-world" directive variables in the parent too, i mean myCtrl.
- How is this possible, i mean child can inherit parent values but how did the parent can inherit child values?
- What is the use the controller in the directive (I know the reason, but I am confused, i just want some light on that if i am missing anything).
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>