Angular Directives: Link to Controller without Services - angularjs

I'm gradually getting the hang of Angular directives and so far, have resorted to creating a service as an intermediary between controllers.
I was just wondering, in the context of directives (and linking functions) is it possible to give the controller access to variables from the linking function? (Without a service or global variables).
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');
});
}
}
};
I want the collection-name attribute's value to be available within my controller, so that I can make appropriate socket calls. Any idea?

You can add a method on the controller and the call it from the link function.
controller: function($scope, socket) {
this.setSocket = function(name){
{...}
}
}
On link:
link: function(scope, element, attrs, controller){
var name = attrs.collectionName;
controller.setSocket(name);
}

They share the same scope, so this should work.
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');
});
}
}
};

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.

Related

AngularJS directive get inner element

I've got next directive:
(function() {
'use strict';
angular
.module('myApp')
.directive('inner', inner);
function inner () {
return {
restrict: 'A',
scope: false,
link: linkFunc
};
function linkFunc (scope, element, attrs) {
}
}
})();
And HTML:
<span inner>{{vm.number}}</span>
How can I access vm.number's value in linkFunc? I need to take value exactly from content of the span tag.
There are various ways you can do this but here are the 2 most common ways:
ngModel
You could use ng-model like so in your template:
<span inner ng-model="vm.number">{{vm.number}}</span>
In your directive you require the ngModel where you can pull its value:
.directive( 'inner', function(){
return {
require: 'ngModel',
link: function($scope, elem, attrs, ngModel){
var val = ngModel.$modelValue
}
}
})
declare isolate scope properties
<span inner="vm.number">{{vm.number}}</span>
.directive( 'inner', function(){
return {
scope: { inner:'=' } ,
link: function($scope, elem, attrs){
var val = $scope.inner
}
}
})
Some less common ways:
use $parse service to get the value
Using the template again:
<span inner="vm.number">{{vm.number}}</span>
Let's assume you're going to Firstly you'll need to inject the $parse service in your directive's definition. Then inside your link function do the following:
var val = $parse(attrs.inner)
inherited scope for read only
I don't recommend this, because depending on how you defined your directive's scope option, things might get out of sync:
isolate (aka isolated) scopes will not inherit that value and vm.number will probably throw an undefined reference error because vm is undefined in most cases.
inherited scope will inherit the initial value from the parent scope but could diverge during run-time.
no scope will be the only case where it will stay in sync since the directive's $scope reference is the same scope present in the expression {{vm.number}}
Again I stress this is probably not the best option here. I'd only recommend this if you are suffering performance issues from a large number of repeated elements or large number of bindings. More on the directive's scope options - https://spin.atomicobject.com/2015/10/14/angular-directive-scope/
Well, In Angular directive, Link function can do almost everything controller can.
To make it very simple, we use one of them most of the time.
var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {
$scope.number = 5;
}).directive('inner', function () {
return {
restrict: 'A',
scope: false,
link: function (scope, element, attrs) {
var number = scope.number;
console.log(number);
}
}
});
Inside html :
<div inner ng-model="number">{{number}}</div>
https://plnkr.co/edit/YbXYpNtu7S3wc0zuBw3u?p=preview
In order to take value from HTML, Angular provides ng-model directive which is works on two way data binding concepts.
There are other ways which is already explain by #jusopi :)
cheers!

Inject factory into directive's link function defined OUTSIDE of the directive's scope

I saw the following question (among other similar questions) and it solves the problem of trying to inject a factory into a directive's link function:
Injecting service to Directive
The solutions I've seen keep the link function within the scope of the directive:
angular.module('myapp')
.directive('myDir', function(myService){
return {
restrict: 'E',
scope: {
frame: '='
},
link: function postLinkFn(scope, elem, attr) {
myService.doSomething();
}
};
});
However, I want to be able to separate the postLinkFn outside of the .directive scope for organization, just like I can do with controllers.
Is it possible to separate this function while also injecting a service into it?
.directive('myDir', function(myService){
var deps = { myService: myService };
return {
...
// myService is available as this.myService inside postLinkFn
link: angular.bind(deps, postLinkFn)
};
});
link function doesn't make use of dependency injection and doesn't have lexical this, binding injected dependencies to this is a reasonable move.
Sure you can put your code in a factory and then refer it globally across the app.
angular.module('myapp').factory('myfactory', myService, function(){
return{
var myfac;
my fac = function (myService){
var myItem = myService.doSomething;
return myItem;
};
};
}).
.directive('myDir', function(myService){
return {
restrict: 'E',
scope: {
frame: '='
},
link: myfactory.myItem;
};
});'
Just a little care you need to take is binding your factory with an angular promise $q if your service deals with asynchronous calls.

A confusing case when using controller and controllerAs in a directive

If a directive is using a controller directly, why is calling a method on the controller by referring the controller by its alias, not doing anything?
Imagine we have the following piece of code:
var app = angular.module('App', []);
app.controller('MyController', ['$scope', function($scope) {
$scope.doAction = function() {
alert("controller action");
}
this.doAction2 = function() {
alert("controller action 2");
}
}]);
app.directive('myDirective', [function() {
return {
restrict: 'E',
scope: {},
controller: 'MyController',
controllerAs: 'myCtrl',
bindToController: true,
template: "<a href='#' ng-click='myCtrl.doAction()'>Click it!<a><br><a href='#' ng-click='myCtrl.doAction2()'>Click it #2!<a> " ,
link: function($scope, element, attrs, controller) {
console.log($scope);
}
}
}]);
While the first link won't work, the second will. To make the the first one work, I'd have to drop the alias, i.e. instead of calling the action by ng-click='myCtrl.doAction()' to call it as: ng-click='doAction()'
Shouldn't it work using the alias too? I mean, you are much more likely to find and reuse a controller, where the developers have attached actions to the $scope object and not to this
ControllerAs exposes the controller instance on the scope under $scope[alias].
In your example, the scope looks (conceptually) like this:
$scope = {
$id: 5,
myCtrl: {
doAction2: function(){...}
},
doAction: function(){...}
}
So, you can see why ng-click="myCtrl.doAction()" doesn't work.
The Controller-As approach has some benefits over directly exposing properties on the scope - one is that it does not pollute the scope (and its descendants) with properties that they may not need. It also inherently provides the dot-approach (.) to work properly with ng-model. You can find more information in this SO question/answer.

adding angular dependencies in a link function shared across multiple directives

I have several directives that use the same link function. (The link function adds some extra state and html depending on the use case.) So I declared this as follows:
function common_linkfunc(){...}
var Directive_1 = function($scope, etc) {
return {restrict:"E", ...
link: common_linkfunc,
controller: function($scope, etc) {...}
};
}
Directive_1.$injects = ["$scope", "etc"];
angular.module("module").directive("D1", Directive_1)...;
First change was when link function required $compile. Next I need to add $templateCache and my question is how can I do this systematically?
My first approach was to rewrite common_linkfunc as
function foo($compile, $templateCache) {
return common_linkfunc($compile, $templateCache) {...}
}
and then use this in every directive:
...
link: foo($compile, $templateCache),
...
But this is copy-and-paste! Is there an easier and less error prone way to do the same?
Regardless of the solution, you'll need to pass some argument to your common link function, because Angular won't inject anything into it for you. That being said, I can think of two different approaches:
1) Use arguments
app.directive('foo', function($http, $timeout) {
return {
restrict: 'E',
link: linkFn1.apply(null, arguments)
}
});
function linkFn1($http, $timeout) {
return function(scope, element, attrs) {
// ...
};
}
The downside here is that the order of the arguments in the directive function matters. If some other directive uses a different order, the code won't work properly.
2) Use $injector
app.directive('bar', function($injector) {
return {
restrict: 'E',
link: linkFn2($injector)
}
});
function linkFn2($injector) {
var $http = $injector.get('$http'),
$timeout = $injector.get('$timeout');
return function(scope, element, attrs) {
// ...
};
}
Working Plunker

Angular reusable functions

I have several directives that need to call the same function after doing their thing. This function needs to access the main controller scope, but also modify the DOM. How and where should this function be declared?
You should use a service, services has access to $rootScope, although is it better to keep DOM modification at directive level, in certain cases you can go for it.
angular.module("myModule", [])
.factory("MyService", function ($rootScope) {
return {
myFunction: function () { // do stuff here }
}
})
.directive("MyDirective", function (MyService) {
return {
link: function (scope, iElement, iAttrs) {
// try do keep dom modification here, you have access to MyService,
// let it do the algorithm and try to keep dom modification here.
// PS: you can also inject $rootScope to directives.
};
};
});
If this function needs to access Controller's scope, I would use the scope which is accessible in the directive and pass it as param, like so:
var MyDirective = function() {
var linkFn = function(scope, element, attrs) {
callAwesomeFn(scope);
};
return {
link: linkFn
}
};
Now, where to put it?
if this is utility function, I would put in some utilities namespace, like MyFunctions.callAwesomeFn()
if this is a component which needs to interact with other objects managed by Angular - use Dependency Injection and inject it into directive

Resources