AngularJS directives: link function and scope isolation &
An example to use the link function and the scope isolation "&" inside a directive
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 as ctrl">
<tab-bar items="ctrl.races"
tab-click="ctrl.selectRace($item)"></tab-bar>
<map coords="ctrl.currentRace.coords" />
</div>
<!-- TabBar directive template: it should be a file .html but jsfiddle doesn't allow it, so we can define it as following: -->
<script type="text/ng-template" id="templates/tabbar.tpl.html">
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav" >
<li ng-repeat="tab in items"
ng-click="itemClick(tab)"
ng-class="{'active': current.id === tab.id}">
<a>{{tab.label}}</a>
</li>
</ul>
</nav>
</script>
CSS
li, .pointer { cursor: pointer; }
JavaScript
// Main module
angular.module('myApp', [])
/**
* Main application controller
*/
.controller('AppCtrl', function($scope){
// Races
this.races = [
{ id:1, label: 'Italy', coords: '41.29246,12.5736108'},
{ id:2, label: 'Japan', coords: '37.4900318,136.4664008'},
{ id:3, label: 'USA' , coords: '37.6,-95.665'}
];
this.selectRace = function(race) {
this.currentRace = race;
}
})
/**
* <map> directive
*/
.directive('map',function () {
return {
scope: {
coords: '='
},
template: '<img ng-src="https://maps.googleapis.com/maps/api/staticmap?center={{coords}}&zoom=4&size=800x200"><br/>{{coords}}'
}
})
/**
* <tab-bar /> directive
*/
.directive('tabBar', function(){
return {
restrict: 'E',
scope: {
items: '=',
tabClick: '&'
},
templateUrl: 'templates/tabbar.tpl.html',
link: function(scope) {
scope.itemClick = function(value) {
// Save the clicked item in a reference
scope.current = value;
// Call external functions
//scope.tabClick({$item: value});
}
}
};
});