最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs passing variables to a directive with an inherited (not isolated) scope - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Aug 28, 2013 at 19:03 wmilwmil 3,1892 gold badges23 silver badges24 bronze badges 1
  • Do you mean accessing the parent scope from within the directive code? – Michael Benford Commented Aug 28, 2013 at 19:14
Add a comment  | 

3 Answers 3

Reset to default 14

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");
    }
  }
});

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>

If you don't declare the scope object in the directive, there will be no isolated scope setup and you will get access to the scope that is passed in from where the div is declared in the DOM.

Something like this:

.directive('myDirective', function() {
  return {
    function(scope, element, attrs){
      //scope here = the inherited scope from the DOM
    }
}

So if you have your directive declared in the DIV tag, you don't need to actually send in the value as an attribute - you can just pull it out of the scope.

发布评论

评论列表(0)

  1. 暂无评论