2015-10-26 42 views
0

我有一个标记:我为什么必须经过两次 - 隔离范围的方法参数?

<div ng-controller="ProductController"> 
     <inventory-Product 
       on-report="showData(p.name,p.price)" 
       ng-repeat="p in products" 
       name="{{p.name}}" 
       price="{{p.price}}"> 
     </inventory-Product> 
</div> 

而且一个指令:

myApp.directive("inventoryProduct", function() 
{ 
    return { 
     restrict: "E", 
     scope : { 
      name : "@", 
      price: "@", 
      onReport:"&" 
     }, 
     template: '<div>{{name}} costs {{ price}}$ </div> \ 
        <div>\ 
        <button \ 
         class="btn btn-lg btn-danger" \ 
         ng-click="onReport({name:name,price:price})">\ 
        Change name\ 
        </button>\ 
        </div>' 

    } 
}) 

(代码是工作)

问:

onReport:"&"允许指令调用一些parentScope函数并传入其参数。

好了 - 所以onReport就像委托指向任何功能,在HTML标记被宣布:

on-report="showData(p.name,p.price)" 

但如果该指令的模板已经发送论点:

ng-click="onReport({name:name,price:price})" 

而且parentScope的控制器功能已经知道功能:

$scope.showData = function (name,price) 
    { 
     alert("name="+name+" price="+price) 
    } 

然后为什么我必须提及

on-report="showData(p.name,p.price)" ? 

换句话说再次参数,似乎更符合逻辑写

on-report="showData" 

所以它只是的功能,然后用这个路径去:

enter image description here

我缺少什么?

回答

1

尝试用ng-click="onReport()",它会正常工作。或者试试on-report="showData(name, price)",它也应该可以正常工作。

当您要从指令本身传递参数(将分别称为name和price)时,您可以从指令中使用onReport({name:name,price:price})。如果指令计算值,存储在其自己的分离范围,必须传递给函数它是有用的:呼叫控制器无法访问这些值,因为它们在其范围内不是。

如果控制器已经有值传递给它的作用域中的函数,并且该指令应该执行该函数调用(如您的示例中所示),那么onReport()就是您所需要的。

+0

谢谢。当你说_调用控制器不能访问这些值,因为它们不在其范围内 - - 什么调用控制器?换句话说,我的样本中实际发生了什么? (参数POV),如果控制器没有这些值会怎么样? –

+0

调用控制器是ProductController。它在由该控制器控制的视图内部,该指令被使用。所以showData()是一个暴露在该控制器范围内的函数。 –

+0

*如果控制器没有这些值,那该怎么办?然后你会使用'on-report =“showData(name,price)”',这两个参数将由指令提供,使用'onReport({name:name ,价格:价格})'。 –

相关问题