Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  64] [ 4]  / answers: 1 / hits: 22379  / 11 Years ago, sat, march 30, 2013, 12:00:00

I have have a directive inside an ng-repeater that should set a scope property.
Please see the fiddle here: http://jsfiddle.net/paos/CSbRB/



The problem is that the scope property is given as an attribute value like this:



<button ng-update1=inputdata.title>click me</button>


The directive is supposed to set the scope property inputdata.title to some string. This does not work:



app.directive('ngUpdate1', function() {
return function(scope, element, attrs) {
element.bind('click', function() {
scope.$apply(function() {
scope[ attrs.ngUpdate1 ] = Button 1;
});
});
};
});


However, assigning directly works:



scope[inputdata][title] = Button 1;


Can you please tell me how I can set a scope property with . notation in its name from a directive?



PS: The reason the fiddle is using a repeater is because it makes the directives be in child scopes. When they are in a child scope, you can't write to scope properties that are primitives. That's why I need an object property with . in the name. See the long explanation here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?



Thank you


More From » angularjs

 Answers
7

$parse will solve your problem.



<button ng-update1=inputdata.title>


app.directive('ngUpdate1', function($parse) {
return function(scope, element, attrs) {
var model = $parse(attrs.ngUpdate1);
console.log(model(scope)); // logs test
element.bind('click', function() {
model.assign(scope, Button 1);
scope.$apply();
});
};
});


Fiddle



Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to modify the value, use $parse.



If you don't need to modify the value, you can use $eval instead:



console.log(scope.$eval(attrs.ngUpdate1));

[#79228] Thursday, March 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;