Reputation: 16028
How do I use one way binding in an angular directive? I couldn't find a simple, easy example on this, and the docs aren't exactly easy to follow either:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
Upvotes: 0
Views: 550
Reputation: 16028
You can use the &
operator in a directive, which you can use as follows:
HTML:
<div ng-app="myApp" >
<drink flavor="ctrlFlavor" ng-init="ctrlFlavor = 'blackberry'"> </drink>
<span>Flavor={{ctrlFlavor}}</span>
</div>
Note that you can initialize ctrlFlavor however you wish, you can do it in an ng-init
block or maybe in your controller
, as the JSFiddle below.
JS:
var app = angular.module('myApp', []);
app.directive("drink", function () {
return {
scope: {
flavor: "&"
},
template: '<input value="{{flavor()}}"/>',
};
});
Note especially {{flavour()}
. The magic is that it returns a function, so you cannot set the value.
Fiddle: http://jsfiddle.net/sgx8zdxc/
You can play around with it and note that changing the value in the input will (obviously) leave the value in the parent scope alone. Additionally, I don't think you can do ngModel='flavor()'
either.
Upvotes: 1
Reputation: 1171
Example of One Way Binding :
<body ng-app ng-init="firstName = 'John'; lastName = 'Doe';">
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind="lastName"></span>
</body>
</html>
One way data binding because the model values (here the variables represent the model) are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don't change the values in the model (one way).
Upvotes: 0