AngularJS : Differences among = & @ in directive scope?

标签 angularjs angularjs-directive angularjs-scope isolated-scope

创建 isolate scope 在指令内,我们可以将外部作用域映射到内部作用域。我们已经看到了六种不同的映射到属性的方法:

  1. =属性
  2. &attr
  3. @attr
  4. =
  5. &
  6. @

这些范围映射选项各自有何作用?

最佳答案

这可能会令人困惑,但希望一个简单的例子能够澄清它。首先,让我们将模型绑定(bind)与行为分开。

这里有一个 fiddle 可以帮助将事情联系在一起:http://jsfiddle.net/jeremylikness/3pvte/

并解释...如果您的指令如下所示:

<my-directive target="foo"/> 

那么你的范围有以下可能性:

{ target : '=' } 

这会将scope.target(指令)绑定(bind)到$scope.foo(外部作用域)。这是因为 = 用于双向绑定(bind),当您不指定任何内容时,它会自动将内部作用域上的名称与指令上的属性名称进行匹配。对scope.target 的更改将更新$scope.foo。

{ bar : '=target' } 

这会将scope.bar绑定(bind)到$scope.foo。这是因为我们再次指定双向绑定(bind),但告诉指令属性“target”中的内容应在内部作用域中显示为“bar”。对scope.bar的更改将更新$scope.foo。

{ target : '@' } 

这会将scope.target设置为“foo”,因为@意味着“按字面意思理解”。对scope.target的更改不会传播到您的指令之外。

{ bar : '@target' } 

这会将scope.bar设置为“foo”,因为@从目标属性中获取它的值。对scope.bar 的更改不会传播到指令之外。

现在我们来谈谈行为。让我们假设您的外部范围有这样的:

$scope.foo = function(parm1, parm2) { console.log(parm1 + ": " + parm2); } 

您可以通过多种方式访问​​此内容。如果您的 HTML 是:

<my-directive target='foo'>

然后

{ target : '=' } 

将允许您从指令中调用scope.target(1,2)。

同样的事情

{ bar : '=target' }

允许您从指令中调用scope.bar(1,2)。

更常见的方法是将其建立为一种行为。从技术上讲,& 符号在父级上下文中计算表达式。这很重要。所以我可以:

<my-directive target="a+b" />

如果父作用域有 $scope.a = 1 和 $scope.b = 2,那么根据我的指令:

{ target: '&' } 

我可以调用scope.target(),结果将是3。这很重要 - 绑定(bind)作为函数公开到内部作用域,但指令可以绑定(bind)到表达式。

更常见的方法是:

<my-directive target="foo(val1,val2)"> 

然后你可以使用:

{ target: '&' }

并从指令调用:

scope.target({val1: 1, val2: 2}); 

这将获取您传递的对象,将属性映射到计算表达式中的参数,然后调用行为,本例调用 $scope.foo(1,2);

你也可以这样做:

<my-directive target="foo(1, val)"/>

这会将第一个参数锁定为文字 1,并且来自指令:

{ bar: '&target' }

然后:

scope.bar(5) 

这将调用 $scope.foo(1,5);

关于AngularJS : Differences among = & @ in directive scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21712147/

相关文章:

javascript - 用户登录后如何动态更新指令?

angularjs - ng-show 和 ng-if 滞后于隐藏内容

javascript - 我不能使用 Angularjs 在我的 index.html 中包含另一个 html 页面

javascript - Angular 指令无法使用 Yeoman 工作

angularjs - Karma-webpack:未知提供者:LeaveServiceProvider <- LeaveService

javascript - 无法将动态添加的指令编译到页面中

angularjs - $emit 事件不适用于 ng-if

javascript - AngularJS : directive does not update scope after $http response in parent scope

python - 比较两个 csv 并合并它们

javascript - 如何改善 eslint-plugin-Angular watch 错误?