With my below angular1.x script code for image annotation I have searched for a solution to solve my conversion error but I didn't get many equalents of angular1.x code in angular4. The error is a runtime error for angular1.x when I try to convert into Angular4. See below.
For $inject I use #inject but it is quite difficult to use it in my code for converting angular 1.x image annotation to angular4 image annotation.
Image annoation in angular1.x
------------------------------
annotoriousAnnotateDirective.$inject = ['annotoriousService', 'setTimeout()'];
annotoriousAnnotateDirective(annotoriousService, setTimeout(()=> {
service = {
restrict: 'A',
link: annotateLink,
priority: 100
},
return service;
link.$inject = ['$scope', '$element', '$attributes'];
annotateLink($scope, $element, $attributes)=> {
if ($attributes.src) {
annotoriousService.makeAnnotatable($element[0]);
} else {
$element.bind('load', function () {
$scope.$apply(function () {
annotoriousService.makeAnnotatable($element[0]);
});
});
}
}
}, 200);
annotoriousDirective.$inject = ['$compile', '$rootScope', '$http', '$parse', '$timeout', 'annotoriousService'];
annotoriousDirective($compile, $rootScope, $http, $parse, $timeout, annotoriousService)=> {
let service = {
restrict: 'E',
scope: {
open: '=',
options: '=',
onOpen: '&',
onLoad: '&',
onComplete: '&',
onCleanup: '&',
onClosed: '&'
},
require: 'annotorious',
link: link,
controller: controller,
controllerAs: 'vm'
};
return service;
controller.$inject = ['$scope'];
controller($scope) {
}
link.$inject = ['$scope', '$element', '$attributes'];
function link($scope, $element, $attributes, controller) {
var cb = null;
$scope.$watch('open', function (newValue, oldValue) {
//console.log("watch $scope.open(" + $scope.open + ") " + oldValue + "->" + newValue);
if (oldValue !== newValue) {
updateOpen(newValue);
}
});
$scope.$on('$destroy', function () {
$element.remove();
});
init();
updateOpen(newValue) {
if (newValue) {
init(newValue);
} else {
if (options.annotationsFor) {
let annotatables = $(options.annotationsFor);
annotatables.each(function (idx) {
let item = this;
annotoriousService.makeAnnotatable(item);
});
}
}
}
init(open) {
let options = {
//href: $attributes.src,
annotationsFor: $attributes.annotationsFor,
onOpen() {
if (this.onOpen && this.onOpen()) {
this.onOpen()();
}
},
onLoad() {
if (this.onLoad && this.onLoad()) {
this.onLoad()();
}
},
onComplete() {
onComplete();
if (this.onComplete && this.onComplete()) {
this.onComplete()();
}
},
onCleanup() {
if (this.onCleanup && this.onCleanup()) {
this.onCleanup()();
}
},
onClosed() {
$scope.$apply(function () {
$scope.open = false;
});
if ($scope.onClosed && $scope.onClosed()) {
$scope.onClosed()();
}
}
};
if (options) {
Object.assign(options, this.options);
}
for (let key in options) {
if (options.hasOwnProperty(key)) {
if (typeof(options[key]) === 'undefined') {
delete options[key];
}
}
}
if (typeof(open) !== 'undefined') {
options.open = open;
}
$timeout(function () {
if (options.annotationsFor) {
$(options.annotationsFor).each(function (i) {
var itemToAnnotate = this;
annotoriousService.makeAnnotatable(itemToAnnotate);
});
}
}, 0);
}
My error code:
I found equalent for #Inject in angular4 ,
import { Inject } from '#angular/core';
import { ourservice } from 'servicepath';
export class{
constructor(#Inject(Ourservice / Directive/ etc) private ourservice){
//our functionality
}
}
If any corrections please let me know, I am still looking solution for Image annotation in angular4
I have created a common ModalService and this is used for two diferrnt type of dialogs. CancelDialog and ErrorDialog will be popped up as per parameter passed to service.
Why do we Unit Test when functionality is working fine??
i.e This will show an ErrorDialog
ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');
All is working fine but am stuck with Unit Test. Here is working PLUNKER.
Please help in covering Unit Test for this.
How to do Unit Test for openErrorModal & openCancelModal in below service.
ModalService
// common modal service
validationApp.service('ModalService',
function($uibModal) {
return {
openModal: openModal
};
function openErrorModal(title, message, callback) {
$uibModal.open({
templateUrl: 'ErrorDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openCancelModal(title, message, callback) {
$uibModal.open({
templateUrl: 'CancelDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openModal(title, message, modalType, callback) {
if (modalType === "Error") {
openErrorModal(title, message, callback);
} else {
openCancelModal(title, message, callback);
}
}
}
);
How to Unit Test onOk , onContinue & onDiscard in below controller.
DialogController
//controller fot dialog
validationApp.controller('ErrorDialogCtrl',
function($uibModalInstance, message, title, callback) {
alert('from controller');
var vm = this;
vm.message = message;
vm.onOk = onOk;
vm.onContinue = onContinue;
vm.onDiscard = onDiscard;
vm.callback = callback;
vm.title = title;
function onOk() {
$uibModalInstance.close();
}
function onContinue() {
$uibModalInstance.close();
}
function onDiscard() {
vm.callback();
$uibModalInstance.close();
}
});
You need to separately test service and controllers. For controllers, you need to test that methods of uibModalInstance are called when controller methods are called. You don't actually need to test that dialog closes, when close method is called. That is the task of those who implemented uibModal.
So here is the test for controller:
describe('ErrorDialogCtrl', function() {
// inject the module of your controller
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
it('tests that close method is called on modal dialog', function() {
var $uibModalInstance = {
close: jasmine.createSpy('close')
};
var callback = function() {};
var controller = $controller('PasswordController', { $uibModalInstance: $uibModalInstance, message: {}, callback: callback });
controller.onOk();
expect($uibModalInstance.close).toHaveBeenCalled();
});
});
Here is the simply test for service:
describe('ModalService', function () {
var $injector;
var $uibModal;
// inject the module of your controller
beforeEach(module('app', function($provide) {
$uibModal = {
open: jasmine.createSpy('open')
};
$provide.value('$uibModal', $uibModal);
}));
beforeEach(inject(function (_$injector_) {
$injector = _$injector_;
}));
it('tests that openErrorModal is called', function () {
var modalService = $injector.get('ModalService');
modalService.openModal(null, null, "Error");
expect($uibModal.open).toHaveBeenCalledWith(jasmine.objectContaining({
controller: "ErrorDialogCtrl"
}));
});
});
My angular app has a controller that can be used both in modal mode and in no modal mode. I would like to check in which mode it is. Can someone help me ?
Order controller
$scope.chooseClient = function() {
$uibModal.open({
templateUrl: 'partials/client/edit.html',
controller: 'ClientEditController',
}).result.then(function (client) {
// Modal OK
if (client) {
$scope.model.client = client;
}
}, function (status) {
// Modal cancelado
});
};
Client controller
.controller('ClientEditController',
function ($scope, $location) {
$scope.cancel = function() {
if (//I would check if modal mode) {
$scope.$dismiss('cancel');
} else {
$location.path("/client/list");
}
};
});
You can pass a resolve object with a flag. That will force you to pass the same resolve in your route for the controller, and inject to resolve to the controller.
$scope.chooseClient = function() {
$uibModal.open({
templateUrl: 'partials/client/edit.html',
controller: 'ClientEditController',
resolve: {
isModal: true
}
}).result.then(function (client) {
// Modal OK
if (client) {
$scope.model.client = client;
}
}, function (status) {
// Modal cancelado
});
};
And than check:
.controller('ClientEditController', function ($scope, $location, isModal) {
$scope.cancel = function() {
if (isModal) {
$scope.$dismiss('cancel');
} else {
$location.path("/client/list");
}
};
});
See docs: $uibModal
here is the code:
(function(){
"use strict";
angular.module("dataModule")
.controller("panelController", ["$scope", "$state", "$timeout", "$modal", panelController]);
function panelController($scope, $state, $timeout, $modal){
$scope.property = "panelController";
//how do we do unit test on openCancelWarning.
//i did not find a way to get openCancelWarning function in Jasmine.
function openCancelWarning () {
var cancelModal = $modal.open({
animation: true,
backdrop: "static",
templateUrl: "pages/data/cancel-warning.html",
controller: "cancelWarningController",
size: "sm",
resolve: {
items : function() {
return {
warningTitle : "Are you Sure?",
warningMessage: "There are unsaved changes on this page. are you sure you want to navigate away from this page?Click OK to continue or Cancel to stay on this page"
};
}
}
});
return cancelModal;
}
var resultPromise = openCancelWarning();
var result;
resultPromise.result.then(function(response){
result = response;
});
}
angular.module("dataModule")
.controller("cancelWarningController", ["$scope", "$modalInstance", "items", cancelWarningController]);
function cancelWarningController($scope, $modalInstance, items){
$scope.warningTitle = items.warningTitle;
$scope.warningMessage = items.warningMessage;
$scope.cancel = function() {
$modalInstance.close(false);
};
$scope.ok = function() {
$modalInstance.close(true);
};
}
}());
here is my jasmine unit test code.
describe("Controller: panelController", function () {
beforeEach(module("dataModule"));
var panelController, scope;
var fakeModal = {
result : {
then: function(confirmCallback) {
this.confirmCallback = confirmCallback;
}
},
close: function(confirmResult) {
this.result.confirmCallback(confirmResult);
}
};
beforeEach(inject(function($modal) {
spyOn($modal, "open").andReturn(fakeModal);
}));
beforeEach(inject(function ($controller, $rootScope, _$modal_) {
scope = $rootScope.$new();
panelController = $controller("panelController", {
$scope: scope,
$modal: _$modal_
});
}));
it('test should be true', function () {
var test;
var testResult = panelController.openCancelWarning();
testResult.close(true);
testResult.then(function(response){
test=response;
});
expect(test).toBe(true);
});
});
i wrote above unit test code with the help from Mocking $modal in AngularJS unit tests
i always get below error.
TypeError: 'undefined' is not a function (evaluating 'panelController.openCancelWarning()')
could anyone help this?
I am trying to create a "Todo App" with angularjs ui-router. It has 2 columns:
Column 1: list of Todos
Column 2: Todo details or Todo edit form
In the Edit and Create controller after saving the Todo I would like to reload the list to show the appropriate changes. The problem: after calling $state.go('^') when the Todo is created or updated, the URL in the browser changes back to /api/todo, but the ListCtrl is not executed, i.e. $scope.search is not called, hence the Todo list (with the changed items) is not retrieved, nor are the details of the first Todo displayed in Column 2 (instead, it goes blank).
I have even tried $state.go('^', $stateParams, { reload: true, inherit: false, notify: false });, no luck.
How can I do a state transition so the controller eventually gets executed?
Source:
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos) {
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos.concat(data);
$state.go('todo.details', { id: $scope.todos[0].Id });
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
$state.go('^', $stateParams, { reload: true, inherit: false, notify: false });
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
$state.go('^');
});
};
};
I would give an example (a draft) of HOW TO nest edit into detail. Well, firstly let's amend the templates.
The Detail template, contains full definition of the detail. Plus it now contains the attribute ui-view="editView". This will assure, that the edit, will "replace" the detail from the visibility perspective - while the edit scope will inherit all the detail settings. That's the power of ui-router
<section ui-view="editView">
<!-- ... here the full description of the detail ... -->
</section>
So, secondly let's move the edit state, into the detail
// keep detail definition as it is
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
// brand new definition of the Edit
.state('todo.details.edit', { // i.e.: url for detail like /todo/details/1/edit
url: '/edit',
views: {
'editView': { // inject into the parent/detail view
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
Having this adjusted state and template mapping, we do have a lot. Now we can profit from the ui-router in a full power.
We'll define some methods on a DetailCtrl (remember, to be available on the inherit Edit state)
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.id = $stateParams.id // keep it here
// model will keep the item (todos) and a copy for rollback
$scope.model = {
todos : {},
original : {},
}
// declare the Load() method
$scope.load = function() {
Todos
.get({ id: $stateParams.id })
.then(function(response){
// item loaded, and its backup copy created
$scope.model.todos = response.data;
$scope.model.original = angular.copy($scope.model.todos);
});
};
// also explicitly load, but just once,
// not auto-triggered when returning back from Edit-child
$scope.load()
};
OK, it should be clear now, that we do have a model with the item model.todos and its backup model.original.
The Edit controller could have two actions: Save() and Cancel()
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
// ATTENTION, no declaration of these,
// we inherited them from parent view !
//$scope.id .. // we DO have them
//$scope.model ...
// the save, then force reload, and return to detail
$scope.save = function () {
Todos
.update({ id: id })
.then(function(response){
// Success
$scope.load();
$state.go('^');
},
function(reason){
// Error
// TODO
});
};
// a nice and quick how to rollback
$scope.cancel = function () {
$scope.model.todos = Angular.copy($scope.model.original);
$state.go('^');
};
};
That should give some idea, how to navigate between parent/child states and forcing reload.
NOTE in fact, instead of Angular.copy() I am using lo-dash _.cloneDeep() but both should work
Huge thanks for Radim Köhler for pointing out that $scope is inherited. With 2 small changes I managed to solve this. See below code, I commented where I added the extra lines. Now it works like a charm.
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos) {
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos(data); // No concat, just overwrite
if (0 < $scope.todos.length) { // Added this as well to avoid overindexing if no Todo is present
$state.go('todo.details', { id: $scope.todos[0].Id });
}
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
$scope.search(); // Added this line
//$state.go('^'); // As $scope.search() changes the state, this is not even needed.
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
$scope.search(); // Added this line
//$state.go('^'); // As $scope.search() changes the state, this is not even needed.
});
};
};
I might have faced a similar problem the approach i took was to use $location.path(data.path).search(data.search); to redirect the page then in the controller I caught the $locationChangeSuccess event. I other words I use the $location.path(...).search(...) as apposed to $state.go(...) then caught the $locationChangeSuccess event which will be fired when the location changes occurs before the route is matched and the controller invoked.
var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/api/todo');
$stateProvider
.state('todo', {
url: '/api/todo',
controller: 'ListCtrl',
templateUrl: '/_todo_list.html'
})
.state('todo.details', {
url: '/{id:[0-9]*}',
views: {
'detailsColumn': {
controller: 'DetailsCtrl',
templateUrl: '/_todo_details.html'
}
}
})
.state('todo.edit', {
url: '/edit/:id',
views: {
'detailsColumn': {
controller: 'EditCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
.state('todo.new', {
url: '/new',
views: {
'detailsColumn': {
controller: 'CreateCtrl',
templateUrl: '/_todo_edit.html'
}
}
})
;
})
;
TodoApp.factory('Todos', function ($resource) {
return $resource('/api/todo/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
var ListCtrl = function ($scope, $state, Todos, todo.details) {
/*here is where i would make the change*/
$scope.$on('$locationChangeSuccess', function () {
$scope.search();
$route.reload();
});
$scope.todos = [];
$scope.search = function () {
Todos.query(function (data) {
$scope.todos = $scope.todos.concat(data);
});
};
$scope.search();
};
var DetailsCtrl = function ($scope, $stateParams, Todos) {
$scope.todo = Todos.get({ id: $stateParams.id });
};
var EditCtrl = function ($scope, $stateParams, $state, Todos, $location) {
$scope.action = 'Edit';
var id = $stateParams.id;
$scope.todo = Todos.get({ id: id });
$scope.save = function () {
Todos.update({ id: id }, $scope.todo, function () {
//here is where I would make a change
$location.path('todo.details').search($stateParams);
});
};
};
var CreateCtrl = function ($scope, $stateParams, $state, Todos, $location) {
$scope.action = 'Create';
$scope.save = function () {
Todos.save($scope.todo, function () {
//here is where I would make a change
$location.path('todo.details');
});
};
};
the $locationChangeSuccess event occurs before the route is matched and the controller invoked