When unit testing a directive how to pass its controller - angularjs

I am new to AngularJS and its unit test. Currently I am trying to test a directive with its controller in the template file:
It's template:
<div ng-controller = "SomeController" >
<select ng-model="data.selectedOption"
ng-options="data.code for data in data.availableOptions track by data.code">
</select>
</div>
It's js file:
angular.module('application.directives')
.directive('selector', function () {
return {
restrict: 'E',
templateUrl: 'templates.html'
};
});
Now I have a unit test like:
describe('selector', function () {
beforeEach(module('application.directives','application.templates'));
it('render the correct number of items', inject(function ($rootScope, $compile) {
var element = $compile('<selector></selector>')($rootScope);
$rootScope.$digest();
//I'd like to register the selector's controller here.
}));
});
In the test code, what would be the best way to register the controller? Do I need to create a mock one?
Thanks

If the controller SomeController is in the same module application.directives, you need not have to too anything. The controller will be available while testing the directive.
Here is the sample code in jsfiddle for similar case
If the controller is in different module.
Here is the sample code in jsfiddle for this case

Related

Custom directive is not working/rendering the html on the browser

I have created a custom directive but when I try to render it on browser it is not working.Please see my code and guide me if you can see where I went wrong.
Below is my code
JS
var app = angular.module('main',[]);
app.controller('servicecntr', function ($scope) {
$scope.name='jagdish';
$scope.changeclick= function(){
$scope.name= $scope.name.split('').reverse().join('');
}
})
app.directive('myDirectives', function(){
return{
restrict:'EA',
scope:false,
template: "<div> this is the print out of name {{name}}" + "onclick the modelPannel is <input type='text' ng-model='name'",
}
})
change the scope:true,you are inherited the scope from the parent controller, you are trying to access the name from parent controller,and how you use this directive in html,i don't find that code.

AngularJS: Can't call onClick() when using ng-bind-html [duplicate]

I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview
I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.
controller
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');
$scope.testAlert = function () {
alert('testing')
};
});
HTML
<body ng-controller="MainCtrl">
<div ng-bind-html="trustedHtml"></div>
</body>
$sce.trustAsHtml and ng-bind-html are not meant to build HTML with directives. This technique will not work.
This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.
In short, by the time you link the HTML defined in your trustAsHtml, it is too late for angular to compile (and therefore understand) the ng-click directive.
In order to dynamically add HTML, you should be looking at the $compile service (and/or directives). Docs are here.
For Angular 1.6.1, I found a solution that worked for me.
template:
<div ng-bind-html="trustAsHtml(content);" init-bind> </div>
In controller:
$scope.trustAsHtml = function(string) {
return $sce.trustAsHtml(string);
};
Directive:
.directive('initBind', function($compile) {
return {
restrict: 'A',
link : function (scope, element, attr) {
attr.$observe('ngBindHtml',function(){
if(attr.ngBindHtml){
$compile(element[0].children)(scope);
}
})
}
};
})

Controller method not found when button inside template is pressed

I'm creating a project using NodeJS, Express and AngularJS that will have a search form (added via custom directive) and a search results that must be loaded only after the search button is pressed.
The problem is that the method I have created inside the controller can't be found from the search form.
Here is a sample of my code:
app.js
(function() {
var app = angular.module('app', ['app-directives']);
app.controller('AppController', function() {
this.buttonClick = function() {
alert('Test');
};
});
})();
directives.js
(function(){
var app = angular.module('app-directives', []);
app.directive('searchForm', function() {
return {
retrict: 'E',
templateUrl: '/partials/search-form.html'
};
});
app.directive('searchResults', function() {
return {
retrict: 'E',
templateUrl: '/partials/search-results.html'
};
});
})();
search-form.html
<input type="text" id="query" />
<button onclick="buttonClick">Search</button>
page-content.html
<section id="mainContent">
<search-form></search-form>
<search-results></search-results>
</section>
UPDATE
The second question will be posted in another thread.
About your first question:
You are using onclick attribute instead angular's 'ng-click' in the button search. This could be the problem. And do not forget to also add the 'ng-app' and 'ng-controller' tags. If not, your method will never be visible.
I also would recommend you to use $scope service instead of 'this' for attaching models and functions you later will use in your views.
Regards

Angular script won't run when first loaded

On page load the console log prints but the toggleClass/click won't work I even use angular.element but it has the same result.I need to change state in order for the toggleClass to work.I dunno what's wrong in my code.
.run(['$rootScope', function ($rootScope) {
console.log('test');//this prints test and it's ok
//this part won't load at the first loading of page.
$('.toggle-mobile').click(function(){
$('.menu-mobile').toggle();
$(this).toggleClass('toggle-click');
});
//....
}])
even doing it this way doesn't work.
$rootScope.$on('$viewContentLoaded', function () {
angular.element('.toggle-mobile').on('click', function (event) {
angular.element(this).toggleClass('toggle-click');
angular.element('.menu-mobile').toggle();
event.preventDefault();
});
});
The Angular way to render items is different from "On DOM Ready" that is why we need to treat these as 2 separate things.
Angular could render items later on even after DOM is ready, this could happen for example if there is an AJAX call($http.get) and that is why a directive may be the recommended approach.
Try something like this:
<body ng-controller="MainCtrl">
<div toggle-Me="" class="toggle-mobile"> Sample <div class="menu-mobile">Sample 2</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {}]);
myApp.directive("toggleMe", function() {
return {
restrict: "A", //A - means attribute
link: function(scope, element, attrs, ngModelCtrl) {
$(element).click(function(){
$('.menu-mobile').toggle();
$(this).toggleClass('toggle-click');
});
}
};
});
...
By declaring the directive myApp.directive("toggleMe",... as an attribute toggle-Me="" every time angular generates the input element it will execute the link function in the directive.
Disclaimer: Since the post lacks from a sample html I made up something to give an idea how to implement the solution but of course the suggested html is not part of the solution.

Angular dynamically created directive not executing

Plnkr sample: [http://plnkr.co/edit/jlMQ66eBlzaNSd9ZqJ4m?p=preview][1]
This might not be the proper "Angular" way to accomplish this, but unfortunately I'm working with some 3rd party libraries that I have limited ability to change. I'm trying to dynamically create a angular directive and add it to the page. The process works, at least in the sense where the directive element gets added to the DOM, HOWEVER it is not actually executed - it is just a dumb DOM at this point.
The relevant code is below:
<div ng-app="myModule">
<div dr-test="Static Test Works"></div>
<div id="holder"></div>
<a href="#" onclick="addDirective('Dynamic test works')">Add Directive</a>
</div>
var myModule = angular.module('myModule', []);
myModule.directive('drTest', function () {
console.log("Directive factory was executed");
return {
restrict: 'A',
replace: true,
link: function postLink(scope, element, attrs) {
console.log("Directive was linked");
$(element).html(attrs.drTest);
}
}
});
function addDirective(text){
console.log("Dynamically adding directive");
angular.injector(['ng']).invoke(['$compile', '$rootScope',function(compile, rootScope){
var scope = rootScope.$new();
var result = compile("<div dr-test='"+text+"'></div>")(scope);
scope.$digest();
angular.element(document.getElementById("holder")).append(result);
}]);
}
</script>
While appending the directive to DOM you need to invoke with your module as well in the injector, because the directive drTest is available only under your module, so while creating the injector apart from adding ng add your module as well. And you don't really need to do a scope apply since the element is already compile with the scope. You can also remove the redundant $(element).
angular.injector(['ng', 'myModule']).invoke(['$compile', '$rootScope',function(compile, rootScope){
var scope = rootScope.$new();
var result = compile("<div dr-test='"+text+"'></div>")(scope);
angular.element(document.getElementById("holder")).append(result);
}]);
Demo

Resources