I have to test a directive depending on a parent scope function for its initialisation:
.directive('droppedSnippet', function () {
return {
templateUrl: 'views/dropped-snippet.html',
restrict: 'E',
scope: {
id: '#',
get: '&'
},
link: function postLink(scope, element, attrs) {
var s = scope.get({id: attrs.id});
element.find('.title').text(s.title);
}
};
});
Context, skip if in a hurry: In order to make it easier to imagine (and to discuss the whole idea if you want), on a drop event this directive is added to the document. The directive represents an embed code. During linking the directive, knowing only its id, should fetch its content from a controller and fill its markup.
In order to mock the parent scope created by the controller, i set up the following mock:
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
scope.foo = function() {
return {
title: 'test title',
code: 'test <code>'
};
};
spyOn(scope, 'foo').andCallThrough();
element = angular.element('<dropped-snippet id="3" get="foo(id)"></dropped-snippet>');
element = $compile(element)(scope);
}));
it('calls the scope function', function() {
expect(scope.foo).toHaveBeenCalledWith(3);
});
The test fails, scope.foo is not called. The code works on the server though. I can not find similar examples around. Is this the right way to mock a function in the parent scope?
Try expect(scope.foo).toHaveBeenCalledWith("3");
Or cast it as a number, the # treats it as a String
Related
I have a directive for users to like (or "fave") posts in my application. Throughout my controllers I use $rootScope.$emit('name-of-function', some-id) to update user data when they like a new post, as this is reflected throughout my application. But I can't seem to use $rootScope.$emit in the directive. I receive an error
$rootScope.$emit is not a function
Presumably the $rootScope.$on event which corresponds with this command has not been called yet, so this function does not yet exist? What can be done about this? Is there a better way to arrange this?
var module = angular.module('directives.module');
module.directive('postFave', function (contentService, $rootScope) {
return {
restrict: 'E',
templateUrl: 'directives/post-fave.html',
scope: {
contentId: '#',
slug: '#'
},
link: function ($scope, $rootScope, element) {
$scope.contentFavToggle = function (ev) {
contentId = $scope.contentId;
contentService.contentFavToggle(contentId, ev).then(function (response) {
$rootScope.$emit('dataUpdated', $scope.slug);
if (response) {
$scope.favourite[contentId] = response;
} else {
$scope.favourite[contentId] = null;
}
});
};
console.log("track fave directive called");
}
};
});
from controller:
var dataUpdatedListener = $rootScope.$on('dataUpdated', function (event, slug) {
dataService.clearData(slug);
dataControllerInit();
});
How can I access this rootscope function from within the directive? Thanks.
FYI - "link" has been used in the directive because this is related to an instance of an HTML element which will be used a number of times on the page
link has the following signature, there is no need to add $rootScope injection into link function:
function link(scope, element, attrs, controller, transcludeFn) { ... }
Remove it from link and it will work.
I am working on an angular project and I use a directive to create an isolated scope. The directive looks like this:
var directive = module.directive('question', function () {
return {
restrict: 'E',
templateUrl: 'question.html',
transclude: true,
scope: {
quiz: '=quiz'
},
link: function (scope, attr, element) {
scope.$watch(function () {
return scope.quiz;
},
function (oldVal, newVal) {
scope.currentQuestion = scope.quiz;
});
}
};
});
For I do not want to bind to a property (or field) in my Controller, I created a function and call the directive this way:
<question quiz="quiz.getCurrentQuestion()">... (transcluding stuff)</question>
Please note that quiz is my Controller using the as-Syntax.
The way I process the directive is working, but I don't like to create a two-way-binding ( to an R-value?).
Now I tried to just pass the function using &-binding but this just turns out odd results in the link-function and breaks everything.
Can I use the function-binding using & and somehow call the function (in my template or in the link-function) to get the result I need to make it work like two-way-binding?
Thank you for your help.
EDIT
The return value of the getCurrentQuestion-function is an object which looks like
{
questionNumber: 1,
answers: [],
getQuestionText() : function(...),
...
}
So nothing to special, I hope...
EDIT 2
When I use
...
scope: {
quiz: '&quiz'
}
then in the $watch-function I get
function(locals) { return parentGet(scope, locals); } for scope.quiz
And if I call the function like scope.quiz() I get undefined as result.
Couldn't find any way to watch a function in scope binding. However, there are other solutions. If you want single way binding you can use '#', but that means that you would have to parse the JSON in the watch ( working example):
var directive = module.directive('question', function () {
return {
restrict: 'E',
templateUrl: 'question.html',
transclude: true,
scope: {
quiz: '#'
},
link: function (scope, attr, element) {
scope.$watch('quiz', function (newVal, oldVal) {
scope.currentQuestion = angular.fromJson(newVal);
});
}
};
});
It works, but if you have a high rate of updates, the overhead can be annoying. What I would do, is use a service that holds all the questions, and both controller and directive can talk to. When the current question is changed, the controller should pass to the directive only the id of the new question (using simple # bind), and the directive would query the service for the question.
I have this simple directive:
...
var readyData = {
caption: ctrl.caption,
leftValue: ctrl.leftValue,
rightValue: ctrl.rightValue,
};
$scope.$emit($attrs.id + ".ready", readyData); //$scope is directive's scope and not $rootScope
}
and I have the following test:
describe("Directive: summaryItem", function () {
// load the directive"s module
beforeEach(module("summaryItem"));
it("Should emit the ready event", inject(function ($compile) {
element = angular.element("<summary-item id=\"summaryItem\"></summary-item>");
element = $compile(element)(scope);
scope.$digest();
var dscope = element.scope();
spyOn(dscope, "$emit");
//run code to test
expect(dscope.$emit).toHaveBeenCalledWith("summaryItem.ready");
}));
I am getting the following error:
Expected spy $emit to have been called with [ 'summaryItem.ready' ] but it was never called.
How can I solve this one? Thanks!
Update
For #themyth92 request here is the full Directive's code:
"use strict";
(function (angular) {
/**
* #ngdoc directive
* #name summaryItemApp.directive:summaryItem
* #description
* # summaryItem
*/
angular.module("summaryItem")
.directive("summaryItem", function () {
return {
templateUrl: "views/summary-item.html",
restrict: "E",
transclude: true,
controller: SummaryItemCtrl,
controllerAs: 'ctrl',
bindToController: true,
scope: {
options: "=",
caption: "="
}
};
});
function SummaryItemCtrl($scope, $attrs) {
var ctrl = this;
ctrl.caption = this.caption;
if(this.options) {
ctrl.leftValue = this.options.leftValue;
ctrl.rightValue = this.options.rightValue;
}
var readyData = {
caption: ctrl.caption,
leftValue: ctrl.leftValue,
rightValue: ctrl.rightValue
};
$scope.$emit($attrs.id + ".ready", readyData);
}
}(angular));
There are two problems in your test. First of all, the event will be triggered at the first $scope.$digest() call. In your test, you mock the $emit function after the digest, so this will not work.
Furthermore, because your directive uses an isolate scope, element.scope() does not do what you expect it to do. In this case, element.scope() will return the original scope of the element; element.isolateScope() will return the isolate scope introduced by the directive.
However, there is another way to test this. Because $emit-ted events bubble up to their parent scopes, you could also test that one of the parent scopes received the correct event.
Untested code:
it("Should emit the ready event", inject(function ($compile) {
var emitted = false;
scope.$on('summaryItem.ready', function() {
emitted = true;
});
element = angular.element("<summary-item id=\"summaryItem\"></summary-item>");
element = $compile(element)(scope);
scope.$digest();
expect(emitted).toBe(true);
}));
As an improvement, you can also store the event instead of just true, which allows you to do all kinds of expects on the emitted events.
I'm relative new to AngularJS and trying to create a directive for add some buttons. I'm trying to modify the controller scope from inside the directive but I can't get it to work. Here is an example of my app
app.controller('invoiceManagementController', ['$scope', function ($scope) {
$scope.gridViewOptions = {
isFilterShown: false,
isCompact: false
};
}]);
app.directive('buttons', function () {
return {
restrict: 'A',
template: '<button type="button" data-button="search" title="Filter"><i class="glyphicon glyphicon-search"></i></button>',
scope: {
gridViewOptions: '='
},
transclude: true,
link: function (scope, element, attr, ctrl, transclude) {
element.find("button[data-button='search']").bind('click', function (evt) {
// Set the property to the opposite value
scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown
transclude(scope.$parent, function (clone, scope) {
element.append(clone);
});
});
}
};
});
My HTML like following
{{ gridViewOptions.isFilterShown }}
<div data-buttons="buttons" data-grid-view-options="gridViewOptions"></div>
The scope inside the directive does change but is like isolated, I did try paying with the scope property and transclude but I'm probably missing something, would appreciate some light here
When you modify scope inside of your directive's link function, you are modifying your directive's isolated scope (because that is what you have set up). To modify the parent scope, you can put the scope assignment inside of your transclude function:
transclude(scope.$parent, function (clone, scope) {
// Set the property to the opposite value
scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown
element.append(clone);
});
Ok finally found a solution for this after some more research today. Not sure if the best solution, but this works so good for now.
app.controller('invoiceManagementController', ['$scope', function ($scope) {
$scope.gridViewOptions = {
isFilterShown: false,
isCompact: false
};
}]);
app.directive('buttons', function () {
return {
restrict: 'A',
template: '<button type="button" data-button="search" data-ng-class="gridViewOptions.isFilterShown ? \'active\' : ''" title="Filter"><i class="glyphicon glyphicon-search"></i></button>',
scope: {
gridViewOptions: '='
},
link: function (scope, element, attr, ctrl, transclude) {
element.find("button[data-button='search']").bind('click', function (evt) {
scope.$apply(function () {
// Set the property to the opposite value
scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown;
});
});
}
};
});
I am getting started with AngularJS and have a noob problem that I am not sure how to resolve. I am modifying a value outside of angular (I have put it in the .run section only for demonstration purposes), and then attempting to run $apply so that Angular will notice that the scope needs to be updated.
However, in the following code, the {{currentState}} value gets set to "Initial value" and does not ever update to "Second value".
What is the correct approach to get the value to update?
angular.module("exampleApp", [])
.run(function(userNotificationService) {
userNotificationService.setStatus("Initial value");
setTimeout(function() {
userNotificationService.setStatus("Second value");
}, 1000);
})
.factory('userNotificationService', function($rootScope) {
var currentState = 'Unknown state'; // this should never be displayed
return {
setStatus: function(state) {
$rootScope.$apply(function() {
currentState = state;
});
},
getStatus: function() {
return currentState;
}
};
}).directive('currentState', function(userNotificationService) {
return {
restrict: 'AE',
scope: false, // set to false so that directive scope is used for transcluded expressions
link: function(scope) {
scope.currentState = userNotificationService.getStatus();
}
};
}).controller("defaultCtrl", function ($scope) {
// does nothing
});
And the html is the following:
<body ng-controller="defaultCtrl">
<div current-state>
current state: {{ currentState }}
</div>
</body>
If your use-case involves a timer, then Angular provides its own timer service called $interval which wraps the call in a scope.$apply for you. You should use that instead of setTimeout.
Now in this case, since you need a one way binding between a service and a value in your scope, you can set up a $watch in your directive:
.directive('currentState', function(userNotificationService) {
return {
restrict: 'AE',
scope: false, // set to false so that directive scope is used for transcluded expressions
link: function(scope) {
scope.$watch(function () { return userNotificationService.getStatus(); }, function (newVal) {
scope.currentState = userNotificationService.getStatus();
});
}
};
Ideally how you would do it is by creating this one way (or two way) binding in your controller (which you have left empty). The $scope you define on the controller will be available to the directive (if you set $scope: false or $scope: true), and then you can leave the link function empty.