角指令:链接到无需服务的控制器
-
20-12-2019 - |
题
我逐渐掌握了角度指令,到目前为止,已经采取了作为控制器之间的中间人创建服务。
我只是想知道,在指令(链接功能)的上下文中,可以使控制器从链接功能提供对变量的?(没有服务或全局变量)。
module.exports = function() {
return {
restrict: 'A',
templateUrl: 'partials/collection',
link: function(scope, element, attrs) {
var name = attrs.collectionName;
// from here
},
controller: function($scope, socket) {
$scope.models = [];
// to here
socket.on('ready', function() {
socket.emit(name + '/get');
});
}
}
};
.
我希望Collection-name属性在我的控制器中可用的值可用,以便我可以制作适当的套接字呼叫。任何想法?
解决方案
它们共享相同的范围,所以这应该有效。
module.exports = function() {
return {
restrict: 'A',
templateUrl: 'partials/collection',
link: function(scope, element, attrs) {
scope.name = attrs.collectionName;
// from here
},
controller: function($scope, socket) {
$scope.models = [];
// to here
socket.on('ready', function() {
socket.emit($scope.name + '/get');
});
}
}
};
. 其他提示
您可以在控制器上添加方法,并从链接功能调用它。
controller: function($scope, socket) {
this.setSocket = function(name){
{...}
}
}
.
在链接:
link: function(scope, element, attrs, controller){
var name = attrs.collectionName;
controller.setSocket(name);
}
. There are a couple of ways of doing what you want
Just put everything in the link function. You can set functions and variables on the scope just like you might put in a controller.
Just put everything in the controller, in terms of setting scope variables or functions. It is injected with
$attrs
, which contains the normalised attribute values, so you have access to the attributes if you need them.
As far as I know, in most cases it doesn't make a difference where you assign variables or functions on the scope. The main difference between the two is that if you want to give your directive a public API, so other directives can communicate to it via require
, then you must use this.something
in the controller.
There maybe a better way to do it, but I've managed to get around the problem by changing my controller functions dependencies to include an $element argument. Then just used jqLite to get the value of the attribute in question.
controller: function($scope, $element, socket) {
var name = $element.attr('collection-name');
}
It's not fantastically elegant, but it works.