HG2D - Scope: {} in AngularJS
Learn how to use scope in Directives in AngularJS
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<div class='well'>
Bound to $rootScope: <input type="text" ng-model="parent">
<div child parent='{{parent}}' shout="shout()"></div>
</div>
<div class='form well' ng-controller="OneCtrl">
ng-controller="OneCtrl"<br/>
<input type="text" ng-model="children"><br/>
I am {{children}} and my grandfather is {{parent}}
<div child parent="{{parent}}" children="children" shout="shout()"></div>
</div>
JavaScript
var App = angular.module('App', []);
App.run(function($rootScope) {
$rootScope.parent = 'ROOT';
$rootScope.shout = function() {
alert("I am bound to $rootScope");
};
});
App.directive('child', function() {
return {
restrict: 'A',
scope: {
parent: '@',
children: '=',
shout: '&'
},
template: '<div class="btn btn-link" ng-click="shout()">I am a directive and my father is {{parent || "NIL"}} as well as {{children || "NIL"}}</div>'
};
});
App.controller('OneCtrl', function($scope) {
$scope.children = 'The One';
$scope.shout = function() {
alert('I am inside ng-controller');
};
});