javascript 如何在指令链接中访问控制器功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29193261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access controller functions in directive link?
提问by luzny
How to access directive controller functions from directive link? Bellow controller passed to link is empty, I would like to get in it show() hide() functions.
如何从指令链接访问指令控制器功能?传递给链接的波纹管控制器是空的,我想在其中加入 show() hide() 函数。
My current directive:
我目前的指令:
app.directive('showLoading', function() {
return {
restrict: 'A',
// require: 'ngModel',
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
return {
show: function() {
alert("show");
},
hide: function() {
alert("hide");
}
};
},
link: function($scope, $element, $attrs, controller) {
$scope.$watch('loading', function(bool) {
if (bool) {
controller.show();//undefined
} else {
controller.hide();
}
});
}
};
});
回答by New Dev
Publishing on the scope can work, but not the best practice, since it "pollutes" the scope. The proper way to communicate with own controller is to requireit - then it will become available as a parameter to the linkfunction, along with other required directives.
在范围上发布可以工作,但不是最佳实践,因为它“污染”了范围。与自己的控制器通信的正确方法是require它 - 然后它将作为link函数的参数以及其他必需的指令可用。
The other issue is with how you expose functions on the controller - this is done by using this.someFn, not by returning an object.
另一个问题是如何在控制器上公开函数 - 这是通过使用this.someFn而不是通过返回对象来完成的。
app.directive('showLoading', function() {
return {
restrict: 'A',
require: ['ngModel', 'showLoading'], // multiple "requires" for illustration
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
this.show = function() {
alert("show");
};
this.hide = function() {
alert("hide");
};
},
link: function($scope, $element, $attrs, ctrls) {
var ngModel = ctrls[0], me = ctrls[1];
$scope.$watch('loading', function(bool) {
if (bool) {
me.show();
} else {
me.hide();
}
});
}
};
});
回答by Shaxrillo
You have some kind of problem inside of controller function
您在控制器功能内部有某种问题
Here is code working fine
这是代码工作正常
app.directive('showLoading', function() {
return {
restrict: 'AE',
// require: 'ngModel',
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
$scope.show = function() {
alert("show");
},
$scope.hide = function() {
alert("hide");
}
},
link: function($scope, $element, $attrs) {
$scope.$watch('loading', function(bool) {
if (bool) {
$scope.show();//undefined
} else {
$scope.hide();
}
});
}
};
});

