[英]AngularJS directive - passing function as argument to “&” attribute
我非常深刻地了解angular directive
,並且我正在嘗試做一些非常簡單的事情,我認為它不受角度的支持。
我正在嘗試將函數作為參數傳遞給指令隔離范圍(類型&
)。
我只想將“ @
”范圍值傳遞給我的控制器中實現的函數。
看起來用參數調用“ &
”scope屬性似乎是不可能的。
<div ng-app="MyApp">
<div ng-controller="MyController">
<testkeyvalue accept="blabla" key='keyA' value='valueA' />
</div>
</div>
var myApp = angular.module('MyApp', [])
myApp.directive('testkeyvalue', function ()
{
return {
restrict: 'E',
replace: true,
scope: {
key: '@',
value: '@',
accept: "&"
},
template: '<div><label class="control-label">{{key}}</label><br/>' +
'<label class="control-label">{{value}}</label>' ,
link: function (scope, element, attrs)
{
var arr = ["key", "value", "accept"];
for (var i = 0, cnt = arr.length; i < arr.length; i++)
{
scope.$watch(arr[i], function ()
{
cnt--;
if (cnt <= 0)
{
fireaccept()
}
});
}
var fireaccept = function ()
{
//This is the problem
//I can't deliver this arguments to the "blabla" function im my controller
scope.accept(scope.key, scope.value);
}
}
};
});
myApp.controller('MyController', function ($scope, $window)
{
$scope.blabla = function (key, val)
{
$window.alert("key:" + key + " val: " + val);
};
});
以下是完整的演示: http : //jsfiddle.net/chezih/y85Ft/401/
我已經讀過這個問題: AngularJS:如何將參數/函數傳遞給指令?
但它不是我想要的,我只想注冊控制器,從指令內部觸發的事件(事件可以傳遞參數)。
有辦法做到這一點嗎?
這是這樣的:
http://jsfiddle.net/Pascalz/hr8zua7q/
<div ng-app="MyApp">
<div ng-controller="MyController">
<testkeyvalue accept="blabla(key, val)" key='keyA' value='valueA' />
</div>
</div>
var myApp = angular.module('MyApp', [])
myApp.directive('testkeyvalue', function ()
{
return {
restrict: 'E',
replace: true,
scope: {
key: '@',
value: '@',
accept: "&"
},
template: '<div><label class="control-label">{{key}}</label><br/>' +
'<label class="control-label">{{value}}</label>' ,
link: function (scope, element, attrs)
{
var arr = ["key", "value", "accept"];
for (var i = 0, cnt = arr.length; i < arr.length; i++)
{
scope.$watch(arr[i], function ()
{
cnt--;
if (cnt <= 0)
{
fireaccept()
}
});
}
var fireaccept = function ()
{
//This is the problem
//I can't deliver this arguments to the "blabla" function im my controller
scope.accept({key:scope.key, val:scope.value});
}
}
};
});
myApp.controller('MyController', function ($scope, $window)
{
$scope.blabla = function (key, val)
{
$window.alert("key:" + key + " val: " + val);
};
});
正如Jussi Kosunen在評論中所說,您可以使用“=”運算符而不是“&”來訪問函數作為隔離范圍中的變量。
最小指令可能如下所示:
directive('exDir', function () {
return {
scope: {isolateScopeFunction: "=fun"},
template: '<button ng-click="isolateScopeFunction(\'inside isolateScope\')">press</button>'
};
});
你會像這樣使用它:
<div ex-dir fun="outerScopeFunctionName"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.