Angularjs将变量传递给具有继承(而非隔离)作用域的指令

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

本文关键字:隔离 作用域 指令 继承 变量 Angularjs      更新时间:2023-09-26

如果我使用一个独立的作用域,我可以通过一个属性传递一个变量。

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

然后,在指令的Javascript 上

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

有什么方法可以对继承的作用域执行类似的操作吗?link函数只是传递字符串。

现在我正在自己解析变量,并将其与作用域进行匹配$父母亲似乎应该有一个助手函数或更简单的方法来实现它。

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

使用以下代码:

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

你可以使用

attrs

元素,以获取分配给该指令的所有atribute。

然后,您可以简单地将attr分配给任何范围,并在e.x模板中使用它。

scope.someValue = attrs.attrName;

综上所述:

指令:

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

指令模板:

<div> {{someValue}} <div>

指令调用

<my-directive attrName="foo"> </my-directive>

如果您不在指令中声明scope对象,将不会有独立的scope设置,您将可以访问从DOM中声明div的位置传入的scope。

类似这样的东西:

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

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