Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs passing variables to a directive with an inherited (not isolated) scope

If I'm using an isolated scope I can pass a variable over an attribute.

ie

<my-directive baz='foo.bar'>

Then, on the directive's Javascript

.directive('myDirective', function() {
  return {
    scope: {
      'baz': '='
    }
  }
});

Is there any way to do something similar with an inherited scope? The link function just passes strings.

Right now I'm parsing the variable myself and matching it to scope.$parent. It seems like there should be a helper function or and easier way to do it.

like image 320
wmil Avatar asked Aug 28 '13 19:08

wmil


2 Answers

Use $eval or $parse:

<my-directive baz='foo.bar'>

.directive('myDirective', function($parse) {
  return {
    scope: true,
    link: function(scope, element, attrs) {
        console.log(scope.$eval(attrs.baz));
        var model = $parse(attrs.baz);
        console.log(model(scope));
        // if you want to modify the value, use the model, not $eval:
        model.assign(scope, "new value");
    }
  }
});
like image 50
Mark Rajcok Avatar answered Oct 13 '22 12:10

Mark Rajcok


with this code:

link: function(scope, elem, attrs) {}

you can use

attrs

element to get all atributes assign to this directive.

then you can simple assign attrs to any scope and use it in your e.x templae.

scope.someValue = attrs.attrName;

To sum up:

Directive:

  link: function(scope, elem, attrs) {
        scope.someValue = attrs.attrName;
    }

Directive template:

<div> {{someValue}} <div>

Directive call

<my-directive attrName="foo"> </my-directive>
like image 28
bmazurek Avatar answered Oct 13 '22 13:10

bmazurek