将参数传递给 Angularjs 指令模板 ng-if

Passing parameter to Angularjs directive template ng-if

PLUNKR

是否可以将参数传递给 ng-if 中的指令模板?

index.html:

<my-directive showName="John"></my-directive>

template.html:

<h1 ng-repeat="customer in customers" ng-if="customer.name === showName ">
  {{customer.name}} is {{customer.age}}
</h1>

理想情况下,上面的示例只会显示 John 的数据。 也许这不是正确的方法? 因为当我在指令中使用 scope: { showName = '@' } 时,ng-repeat 似乎不再起作用了?

一旦你使用

scope: {
   showName:'='
}

发生了两件事:

  1. 指令的参数定义为名称 show-name。不是 showName.

  2. 指令范围被隔离。这意味着它无法访问在父作用域中定义的 customers 。您也必须在参数中传递它们。

此外,您应该在 ng-repeat 上使用过滤器,而不是使用 ng-ifng-repeat。否则你会遇到优先级问题(ng-ifng-repeat 之前执行)。

您应该改用过滤器。

为此,您必须更改模板中的表达式:

<h1 ng-repeat="customer in customers | filter:{name: showName}">
  {{customer.name}} is {{customer.age}}
</h1>

这将只过滤匹配的名称属性。

要有一个独立的范围,您应该将您的属性绑定到指令中的本地范围变量:

scope: {
  customers: '=', //two way binding of the object
  showName: '@'   //string evaluation
}

但是由于你有一个独立的范围,你还应该像这样添加属性 customers:

<my-directive show-name="John" customers="customers"></my-directive>

这是工作 plunkr

如果需要,您还可以更进一步,将您的节目名称绑定到输入字段:

<input ng-model="search" />
<my-directive customers="customers" show-name="search"></my-directive>

因此您还必须将绑定更改为双向绑定:

scope: {
   customers: '=',
   showName: '='
}