The initial setup:
<div ng-app="drinkApp">
<div ng-controller="AppCtrl">
<div drink flavor="strawberry"></div>
</div>
</div>
var app = angular.module('drinkApp', []);
app.controller("AppCtrl", function ($scope) {
})
app.directive("drink", function () {
return {
scope: {},
template: '<div>{{ flavor }}</div>',
link: function (scope, element, attrs) {
scope.flavor = attrs.flavor;
}
};
});
This setup serves to take the flavor attribute passed from the view, assign it to the flavor value in the scope, and insert it into a div, which is dropped into the drink element directive.
With the @ operator, we are able to substitute the entire link function into a single attribute within the scope object. This operator serves to do exactly the same thing as what the link function does above: extract an attribute by name, and assign it to the scope.
app.directive("drink", function () {
return {
scope: {
flavor: "@"
},
template: '<div>{{ flavor }}</div>',
};
});
@ operator
This onehungrymind post has some terrific examples and elaborations on isolate scope The attributes are evaluated to a string before they are handed off to the directive’s scope.
var app = angular.module('drinkApp', []);
app.controller("AppCtrl", function ($scope) {
$scope.ctrlFlavor = "blackberry";
})
Here, the interpolated ctrlFlavor inside the flavor attribute value will evaluate to “blackberry” for the directive.
Adding in a model
<div ng-app="drinkApp">
<div ng-controller="AppCtrl">
<input type="text" ng-model="ctrlFlavor">
<div drink flavor="{{ ctrlFlavor }}"></div>
</div>
</div>