i have a function which i call more than once ( in different directives).
So is there a way to call a function in every directive?
One solution would be to make the function as a service.
But the service does need a return value, doesn´t it?
this.changeDesign = function (currentstep) {
//do something
};
this method I call many times.
You should consider to avoid using global variables or put something on the global scope. Maybe it works now, but if your project gets bigger, you will probably get a lot of problems. More infos for example: https://gist.github.com/hallettj/64478
Here is an example, how you can use a factory, which you can inject into your directives (coding style inspired by John Papa https://github.com/johnpapa/angular-styleguide#factories):
(function () {
"use strict";
angular.module('my-app').provider('MyFactory', MyFactory);
MyFactory.$inject = [];
function MyFactory() {
var service = {
changeDesign: myChangeDesignImpl
};
function myChangeDesignImpl() { }
this.$get = function() {
return service ;
};
}
})();
You can now inject your service into a directive like this:
(function () {
"use strict";
angular.module('my-app').directive('MyDirective', MyDirective);
MyDirective.$inject = ["MyFactory"];
function MyDirective(MyFactory) {
var directive = {
restrict: 'E',
template: "/template.html",
link: link
};
return directive;
function link(scope, el, attr) {
MyFactory.changeDesign();
}
}
})();
you can do it in a directive that you will delcare on your elements.
angular.module('myDesignModule', [])
.directive('myDesignDirective', function() {
return {
link: function(scope, element, attrs, ctrl){
element.addClass("myClass");
}
};)
Related
I'm trying to figure out AngularJS directives. I've got the following JSFiddle with an example of something I'm trying to do. https://jsfiddle.net/7smor9o4/
As you can see in the example, I expect the vm.alsoId variable to be equal to vm.theId. In the template vm.theId displays the correct value but vm.alsoId does not.
What am I doing wrong? How could I accomplish my goal.
If it helps the final idea is to execute something as the following:
function directive(service) {
var vm = this;
vm.entity = null;
init();
function init() {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
}
}
As you've noticed, the bindToController bindings are not immediately available in the controller's constructor function (unlike $scope, which are). What you're looking for is a feature introduced with Angular 1.5: Lifecycle Hooks, and specifically $onInit.
You had the right idea; simply replace your init function definition and invocation as follows:
vm.$onInit = function () {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
};
And here is your updated fiddle.
(Alternatively, without this solution, you'd have needed a watch.)
Angular recommends that you bind a controller "only when you want to expose an API to other directives. Otherwise use link."
Here's a working fiddle using the link function.
angular.module('app', [])
.directive('directive', directive);
angular.element(function() {
angular.bootstrap(document, ['app']);
});
function directive() {
return {
restrict: 'E',
scope: {
theId: '<'
},
template: `
alsoId: <span ng-bind="alsoId"></span>
theId: <span ng-bind="theId"></span>`,
link: link
};
}
function link(scope, element, attrs) {
init();
function init() {
scope.alsoId = scope.theId;
}
}
I have a page with two directives. I need to invoke a function in one directive from the other. I have added the function to the $element object of the first directive and used jQuery to invoke it from the other. Is this the right approach or should I be using a context object shared by both directives?
//inside directive 1 link fn
$element[0].foo = function(){
console.log("test");
}
...
//inside directive 2 link fn
$('.className').foo()
The two directives are elements on a page with a shared controller. Each has an isolated scope. This seems to work well. Are there any reasons why I should not do this?
are the 2 directives sharing the same controller? If so, you could call a function on the controller from one directive which would "notify" the other. Or, you could use events, check this answer here
This is not the way you should do it. Try to avoid using $element, it does DOM manipulations which are slow and Angular takes care of by itself. To invoke a function in directiveB, triggered from directiveA, you better make a service.
angular.service('Communication', function () {
var _listeners = [];
return {
addListener: function (callback) {
_listeners.push(callback);
},
removeListener: function () {/* Clean up */},
invokeListeners: function (data) {
_listeners.forEach(function (listener) {
listener(data);
});
}
}
});
angular.directive('directiveB', ['Communication', function (Communication) {
return {
restrict: 'AE',
scope: {},
controller: directiveB
};
function directiveB (scope, element, attrs) {
Communication.addEventListener(function (data) { /* Do stuff with data */ });
}
}]);
angular.directive('directiveA', ['Communication', function (Communication) {
return {
restrict: 'AE',
scope: {},
controller: directiveA
};
function directiveA (scope, element, attrs) {
// trigger event in directive B
Communication.invokeListeners('test');
}
}]);
What I want to do:
I'm trying to create a function within a directive that can be called from the $rootScope.
The Problem:
It seems to only be working on the last item in the DOM which has this directive. I'm guessing that what's happening is rootScope.myFunction gets overwritten each time this directive runs.
The Question:
How can I create one function in the $rootScope which, when called, runs the internal function for each directive instead of just the last one?
The Relevant Code:
(function() {
angular.module('home')
.directive('closeBar', closeBar);
closeBar.$inject = ['$rootScope', '$window'];
function closeBar(rootScope, window) {
return {
scope: true,
restrict: 'A',
link: function(scope, element, attrs) {
var myFunction = function() {
// do stuff
};
myFunction();
rootScope.myFunction = function() {
myFunction();
};
}
};
}
})();
Then in a different script, I want to call:
rootScope.myFunction();
Note, I'm not allowed to share actual code from the project I'm working on so this is a more general question not tied to a specific use case.
A simple solution would be to create a special function in your rootScope that accepts functions as an argument, and pushes it into an array, and you will be able to invoke that function later which will call all the registered functions.
angular.module('myApp').run(['$rootScope', function($root) {
var functionsToCall = [];
$root.registerDirectiveFunction = function(fn, context) {
context = context || window;
functionsToCall.push({fn: fn, context: context});
}
$root.myFunction = function(args) {
functionsToCall.forEach(function(fnObj) {
fnObj.fn.apply(fnObj.context,args);
});
}
}
And in your directive:
link: function($scope, $el, $attr) {
function myFunct() {
}
$scope.$root.registerDirectiveFunction(myFunct, $scope);
//call it if you want
$scope.$root.myFunction();
}
This should cover your scenario.
I wrote a directive that will conditionally add a wrapper element which I modeled after Angular's ngIf directive. The directive works great when running in production, but in trying to add unit tests the $animate.enter function never calls my callback function. This is causing all my unit tests to fail when it assumes that the wrapper is not suppose to be there.
I'm using Angular.js version 1.2.16 and loading ngMock and ngAnimate for the unit test. The code fires the ngAnimate enter function, but then it never fires the callback.
You can view the code here, just uncomment the appSpec.js script tag and the directive no longer works.
Does anyone now how to trigger $animate.enter to call my callback function in a unit test?
addWrapperIf.js
angular.module('myModule', ['ngAnimate'])
.directive('addWrapperIf', ['$animate', function($animate) {
return {
transclude: 'element',
priority: 1000,
restrict: 'A',
compile: function (element, attr, transclude) {
return function ($scope, $element, $attr) {
var childElement, childScope;
$scope.$watch($attr.addWrapperIf, function addWrapperIfWatchAction(value) {
if (childElement) {
$animate.leave(childElement);
childElement = undefined;
}
if (childScope) {
childScope.$destroy();
childScope = undefined;
}
// add the wrapper
if (value) {
childScope = $scope.$new();
transclude(childScope, function (clone) {
childElement = clone
$animate.enter(clone, $element.parent(), $element);
});
}
// remove the wrapper
else {
childScope = $scope.$new();
transclude(childScope, function (clone) {
$animate.enter(clone, $element.parent(), $element, function() {
childElement = clone.contents();
clone.replaceWith(clone.contents());
});
});
}
});
}
}
};
}]);
addWrapperIfSpec.js
var expect = chai.expect;
describe('addWrapperIf', function () {
var $template;
var $compile;
var $scope;
beforeEach(window.module('myModule'));
beforeEach(inject(function(_$compile_, $rootScope){
$compile = _$compile_;
$scope = $rootScope.$new();
}));
function compileDirective(template) {
$template = $compile(template)($scope)[0];
$scope.$apply();
}
it('should output the correct values with default options', function() {
compileDirective('<div add-wrapper-if="false"><span>child</span></div>');
console.log($template); // <div add-wrapper-if="false"><span>child</span></div>
});
});
So I figured out what you have to do. I dug into the code and found out that inside ngAnimate it pushes the callback function to $$asyncCallback. $$asyncCallback has a flush function that will call any functions pushed onto it. To get $animate.enter to fire the callback, you have to inject $$asyncCallback into your unit test and then call $$asyncCallback.flush(). This will then run your callback function.
You can see this in this Plunker.
I want to have a call back function on a directive I wrote, without creating an isolated scope. The directive simply makes the element resizeable, and thus doesn't need a separate scope (and it's desirable NOT to have isolated scope in this case, I think).
What is the best way to do this? I tried,
.controller("MyController", function ($scope) {
$scope.myFunc = function () {
console.log("test");
};
})
.directive('resizeable', function ($document, $parse) {
return function (scope, element, attr) {
var func = $parse(attr.onFunc);
}
}
with
<div class="main" resizeable="" on-Func="myFunc()">
How to do this?
Try this JSFiddle.
You're close, here is what I'd do:
.directive('resizeable', ['$document', '$parse', function ($document, $parse) {
return {
link: function ($scope, $element, $attrs) {
var func = $parse($attrs.resizeable);
// do stuff...
func($scope);
}
};
}]);
And the HTML would be:
<div data-resizeable="myFunc()"></div>
Here is a working demo: http://plnkr.co/edit/as6Tylj0zPpjVsUaDDC6?p=preview
on-Func="myFunc"
Without parenthesis. And in the directive:
var func = scope[attr.onFunc];
The directive is in the same scope as the controller. So you can directly refernece the function.