9

如果我使用的是隔离范围,我可以通过属性传递一个变量。

IE

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

然后,在指令的 Javascript 上

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

有没有办法用继承的范围做类似的事情?链接函数只是传递字符串。

现在我正在自己解析变量并将其与 scope.$parent 匹配。似乎应该有一个辅助功能或更简单的方法来做到这一点。

4

3 回答 3

14

使用$eval$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");
    }
  }
});
于 2013-08-28T19:26:59.430 回答
3

使用此代码:

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

您可以使用

attrs

元素来获取分配给该指令的所有属性。

然后您可以简单地将 attrs 分配给任何范围并在您的前模板中使用它。

scope.someValue = attrs.attrName;

总结一下:

指示:

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

指令模板:

<div> {{someValue}} <div>

指令调用

<my-directive attrName="foo"> </my-directive>
于 2014-07-22T14:47:59.710 回答
0

如果您没有在指令中声明作用域对象,则不会有隔离作用域设置,并且您将可以访问从 DOM 中声明 div 的位置传入的作用域。

像这样的东西:

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

因此,如果您在 DIV 标记中声明了指令,则不需要实际将值作为属性发送 - 您只需将其拉出范围即可。

于 2013-08-28T19:27:14.607 回答