Unit-testing directive controllers in Angular without making controller global

I prefer at times to include my controller along with the directive so I need a way to test that. First the directive angular.module(‘myApp’, []) .directive(‘myDirective’, function() { return { restrict: ‘EA’, scope: {}, controller: function ($scope) { $scope.isInitialized = true }, template: ‘<div>{{isInitialized}}</div>’ } }) Then the tests: describe(“myDirective”, function() { var el, scope, … Read more

How to understand the `terminal` of directive?

Priority The priority is only relevant when you have multiple directives on one element. The priority determines in what order those directives will be applied/started. In most cases you wouldn’t need a priority, but sometimes when you use the compile function, you want to make sure that your compile function runs first. Terminal The terminal … Read more

AngularJS accessing DOM elements inside directive template

I don’t think there is a more “angular way” to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page: { template: ‘<div>’ + ‘<div class=”title”>{{title}}</div>’ + ‘<div class=”body” ng-transclude></div>’ + ‘</div>’, link: function(scope, element, attrs) { // Title element var title = … Read more

Using ng-click vs bind within link function of Angular Directive

You may use a controller in directive: angular.module(‘app’, []) .directive(‘appClick’, function(){ return { restrict: ‘A’, scope: true, template: ‘<button ng-click=”click()”>Click me</button> Clicked {{clicked}} times’, controller: function($scope, $element){ $scope.clicked = 0; $scope.click = function(){ $scope.clicked++ } } } }); Demo on plunkr More about directives in Angular guide. And very helpfull for me was videos from … Read more

AngularJS directive dynamic templates

You can set the template property of your directive definition object to a function that will return your dynamic template: restrict: “E”, replace: true, template: function(tElement, tAttrs) { return getTemplate(tAttrs.content); } Notice that you don’t have access to scope at this point, but you can access the attributes through tAttrs. Now your template is being … Read more

Binding variables from Service/Factory to Controllers

You can’t bind variables. But you can bind variable accessors or objects which contain this variable. Here is fixed jsfiddle. Basically you have to pass to the scope something, which can return/or holds current value. E.g. Factory: app.factory(‘testFactory’, function(){ var countF = 1; return { getCount : function () { return countF; //we need some … Read more