Directives angulaires: Lien vers le contrôleur sans services
-
20-12-2019 - |
Question
Je reçois progressivement la suspension des directives angulaires et j'ai jusqu'à présent eu recours à la création d'un service comme intermédiaire entre contrôleurs.
Je me demandais simplement, dans le contexte des directives (et des fonctions de liaison), est-il possible de donner à l'accès au contrôleur aux variables à partir de la fonction de liaison?(Sans service ni variables globales).
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');
});
}
}
};
Je souhaite que la valeur de l'attribut de nom de collection soit disponible dans mon contrôleur, de sorte que je puisse apporter des appels de socket appropriés.Aucune idée?
La solution
Ils partagent la même portée, cela devrait donc fonctionner.
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');
});
}
}
};
Autres conseils
Vous pouvez ajouter une méthode sur le contrôleur et l'appeler à partir de la fonction de liaison.
controller: function($scope, socket) {
this.setSocket = function(name){
{...}
}
}
sur le lien:
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.