问题描述
我知道角指令
得很深,而我试图做一些很简单的,我认为它不是在角支撑。结果
我想传递一个函数作为参数的指令隔离范围(键入&安培;
)。结果
我只是想传递 @
范围值,在我的控制器实现的功能。结果
现在看来似乎是不可能的调用;带有参数&放
scope属性。
I know angular directive
very deeply, and I'm trying to do something very simple, and I think it's not supported in angular.
I'm trying to pass a function as argument to the directive isolated scope (type &
).
I just want to deliver the "@
" scope values to the function implemented in my controller.
It seems like it's impossible to call the "&
" scope attribute with arguments.
<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);
};
});
下面是完整的演示:
我读过这个问题:AngularJS:如何参数/函数传递给指令?结果
但是,这不是我要找的,我只是想注册控制器,将事件从指令(和事件可以传递参数)内触发。
I've read this question: AngularJS: How to pass arguments/functions to a directive?
But it's not what I'm looking for, I just want to register the controller, to event that triggered from inside the directive (and the event can pass arguments).
有什么办法可以做到这一点?
There is any way to do this?
推荐答案
这是工作是这样的:
<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);
};
});
这篇关于AngularJS指令 - 传递函数作为参数传递给&QUOT;&安培;&QUOT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!