AngularJS directives: scope isolation =, @, true, false
In this example I show you how to create AngularJS directives with an isolated scope, illustrating several ways to do it: "=", "@", true and false (default).
by soumya gangamwar
July 26, 2016
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-controller="AppCtrl">
<div class="row">
<div class="col-md-4">
<h3>Controller</h3>
<input type="text" ng-model="user" class="form-control">
<!-- <input type="text" ng-model="data.user" class="form-control"> -->
</div>
<div class="col-md-4">
<h3>Directives</h3>
<h6>1. Scope: false or not defined</h6>
<profile-panel1></profile-panel1>
<h6>2. scope: true </h6>
<profile-panel2 ></profile-panel2>
<h6>3. Isolated scope -> {}</h6>
<profile-panel3></profile-panel3>
<h6>4. Isolated scope -> prop: "="</h6>
<profile-panel4 name="user"></profile-panel4>
<h6>5. Isolated scope -> prop: "@"</h6>
<profile-panel5 name="{{user}}"></profile-panel5>
</div>
<div class="col-md-2"></div>
</div>
</div>
JavaScript
var app = angular.module('myApp', [])
.controller('AppCtrl', function($scope){
$scope.user = 'fabio';
})
// Scope: false (default)
// The directive is in the same scope of the controller
.directive('profilePanel1', function(){
return {
restrict: 'EA',
template: '<input type="text" ng-model="user" class="form-control">'
};
})
// Scope: true
// The directive create a new child scope inherited from parent
.directive('profilePanel2', function(){
return {
restrict: 'EA',
scope: true,
template: '<input type="text" ng-model="user" class="form-control">'
};
})
// Isolated scope
// Note: the directive has its own scope
.directive('profilePanel3', function(){
return {
restrict: 'EA',
scope: {},
template: '<input type="text" ng-model="user" class="form-control">'
};
})
// Directive with isolated scope and a property in two-way binding
.directive('profilePanel4', function(){
return {
restrict: 'EA',
scope: {
name: '='
},
template: '<input type="text" ng-model="name" class="form-control">'
};
})
// Directive with isolated scope and a property in one-way binding
.directive('profilePanel5', function(){
return {
restrict: 'EA',
scope: {
name: '@'
},
template: '<input type="text" ng-model="name" class="form-control">'
};
});