If I have an AngularJS directive without a template and I want it to set a property on the current scope, what is the best way to do it?
For example, a directive tha
I'm surprised no one has mentioned ng-model, the default directive for doing two-data binding. Maybe it's not so well known, but the linking function has a fourth parameter:
angular.module('directive-binding', [])
.directive('twoway',
function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
elem.on('click', function() {
var counter = ngModel.$viewValue ? ngModel.$viewValue : 0
ngModel.$setViewValue(++counter);
scope.$apply();
});
}
};
}
);
On your view
Click Count: {{ counter }}
The fourth parameter is an API for the ngModelController, which has many uses for handling (parsing and formatting, for instance) and sharing data between a directive and a scope.
Here's the updated Plunker.