Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - How to set angular controller object property value from directive in child scope

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...