为什么我必须通过两次 - 隔离范围的方法参数?

时间:2015-10-26 22:42:52

标签: angularjs

我有一个标记:

 <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 个答案:

答案 0 :(得分:1)

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

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

如果控制器已经将值传递给其范围内的函数,并且该指令应该只执行该函数调用(如示例所示),那么onReport()就是您所需要的。