Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set an interpolated value in angular directive?

How do I set the interpolated value in a directive? I can read the correct value from the following code, but I have not been able to set it.

js:

app.directive('ngMyDirective', function () {
    return function(scope, element, attrs) {
        console.log(scope.$eval(attrs.ngMyDirective));

        //set the interpolated attrs.ngMyDirective value somehow!!!
    }
});

html:

<div ng-my-directive="myscopevalue"></div>

where myscopevalue is a value on my controller's scope.

like image 674
Anton Avatar asked May 11 '13 06:05

Anton


Video Answer


2 Answers

Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to change that property's value, I suggest using $parse. (I think the syntax is nicer than $eval's.)

app.directive('ngMyDirective', function ($parse) {
    return function(scope, element, attrs) {
        var model = $parse(attrs.ngMyDirective);
        console.log(model(scope));
        model.assign(scope,'Anton');
        console.log(model(scope));
    }
});

fiddle

$parse works whether or not the attribute contains a dot.

like image 75
Mark Rajcok Avatar answered Sep 17 '22 17:09

Mark Rajcok


If you want to set a value on the scope but don't know the name of the property (ahead of time), you can use object[property] syntax:

scope[attrs.myNgDirective] = 'newValue';

If the string in the attribute contains a dot (e.g. myObject.myProperty), this won't work; you can use $eval to do an assignment:

// like calling  "myscopevalue = 'newValue'"
scope.$eval(attrs.myNgDirective + " = 'newValue'");

[Update: You should really use $parse instead of $eval. See Mark's answer.]

If you're using an isolate scope, you can use the = annotation:

app.directive('ngMyDirective', function () {
    return {
        scope: {
            theValue: '=ngMyDirective'
        },
        link: function(scope, element, attrs) {
            // will automatically change parent scope value
            // associated by the variable name given to `attrs.ngMyDirective`
            scope.theValue = 'newValue';
        }
    }
});

You can see an example of this in this Angular/jQuery color picker JSFiddle example, where assigning to scope.color inside the directive automatically updates the variable passed into the directive on the controller's scope.

like image 24
Michelle Tilley Avatar answered Sep 20 '22 17:09

Michelle Tilley