Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  101] [ 6]  / answers: 1 / hits: 64425  / 11 Years ago, wed, september 18, 2013, 12:00:00

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 that counts button clicks:



<button twoway=counter>Click Me</button>
<p>Click Count: {{ counter }}</p>


With a directive that assigns the click count to the expression in the two way attribute:



.directive('twoway', [
'$parse',
function($parse) {
return {
scope: false,
link: function(scope, elem, attrs) {
elem.on('click', function() {
var current = scope.$eval(attrs.twoway) || 0;
$parse(attrs.twoway).assign(scope, ++current);
scope.$apply();
});
}
};
}
])


Is there a better way to do this? From what I've read, an isolated scope would be overkill, but do I need a child scope? And is there a cleaner way to write back to a scope variable defined in the directive attribute other than using $parse. I just feel like I'm making this too difficult.



Full Plunker here.


More From » angularjs

 Answers
59

Why is an isolate scope overkill? its pretty useful for exactly this kind of thing:



  scope: {
twoway: = // two way binding
},


This is a pretty idiomatic angular solution to this problem, so this is what I'd stick with.


[#75609] Tuesday, September 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;