AngularJS - 自定义指令访问NG-点击 [英] AngularJS - accessing ng-click in custom directive
问题描述
我试图让我的身边指令的头,我可以轻松地使用模板函数抛出了我的HTML,但是,如果我有我的模板内的NG-点击,我怎么能链接函数内访问它?
我的指令:
app.directive('directiveScroll',函数(){
返回{
限制:AE,
替换:'真',
模板:'< DIV CLASS =滚动btns>' +
'< DIV CLASS =左箭头NG点击=scrollLeft(sectionID)>< / DIV>' +
'< DIV CLASS =右箭头NG点击=scrollRight(sectionID)>< / DIV>' +
'< / DIV>,
链接:功能(范围,ELEM,ATTRS){
$ scope.scrollRight =功能(){
的console.log(scrollRight点击);
};
$ scope.scrollLeft =功能(){
的console.log(scrollLeft点击);
};
}
};
});
正如你所看到的,我已经添加了 $ scope.scrollRight
我的链接
的功能,但是在点击,没有出现在控制台中。
如果我把:
$ scope.scrollRight =功能(){
的console.log(scrollRight点击);
};$ scope.scrollLeft =功能(){
的console.log(scrollLeft点击);
};
在我的控制器(和我的指令),它按预期工作。
任何帮助AP preciated。
您链接功能的定义是这样的:
链接:功能(范围,ELEM,ATTRS){..}
但你在 $范围
变量写功能
$ scope.scrollRight =功能(){
的console.log(scrollRight点击);
};
$ scope.scrollLeft =功能(){
的console.log(scrollLeft点击);
};
在这种情况下,$范围是不实际注入链路功能(并且不能注射),所以链路仅仅是与参数的简单函数。您应该更改 $范围
到范围
,它应该工作:
scope.scrollRight =功能(){
的console.log(scrollRight点击);
};
scope.scrollLeft =功能(){
的console.log(scrollLeft点击);
};
I'm trying to get my head around directives, i can easily use the template function to throw out my HTML, however, if i have an ng-click within my template, how can i access it within the link function?
My directive:
app.directive('directiveScroll', function () {
return {
restrict: 'AE',
replace: 'true',
template: '<div class="scroll-btns">' +
'<div class="arrow-left" ng-click="scrollLeft(sectionID)"></div>' +
'<div class="arrow-right" ng-click="scrollRight(sectionID)"></div>' +
'</div>',
link: function(scope, elem, attrs) {
$scope.scrollRight = function () {
console.log("scrollRight clicked");
};
$scope.scrollLeft = function () {
console.log("scrollLeft clicked");
};
}
};
});
As you can see, i have added $scope.scrollRight
to my link
function, however on click, nothing appears in the console.
If i place:
$scope.scrollRight = function () {
console.log("scrollRight clicked");
};
$scope.scrollLeft = function () {
console.log("scrollLeft clicked");
};
In my controller (and out of my directive), it works as expected.
Any help appreciated.
Your link function is defined like this:
link: function(scope, elem, attrs) {..}
however you are writing functions on $scope
variable:
$scope.scrollRight = function () {
console.log("scrollRight clicked");
};
$scope.scrollLeft = function () {
console.log("scrollLeft clicked");
};
In this case $scope is not actually injected into link function (and can't be injected), so link is just simple function with parameters. You should change $scope
to scope
and it should work:
scope.scrollRight = function () {
console.log("scrollRight clicked");
};
scope.scrollLeft = function () {
console.log("scrollLeft clicked");
};
这篇关于AngularJS - 自定义指令访问NG-点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!