Angular 1.5 Component - dependency injection - angularjs

My goal was to use dependency injection of a constant value (the base URL) to use in defining the component's templateUrl property. Nothing so far has worked. The code below is in Typescript
Some explanation: app.core.Iconstants holds the baseUrl value.
app.core.AngularGlobals.appCoreConstants is the string representing "app.core.Constants".
Mind you, I'm just cutting my teeth of Angular.
namespace donationEntry.Components{
"use strict";
class test1 implements ng.IComponentOptions {
public static id: string = AngularGlobals.donationEntry + ".test1";
bindings: any;
controller: any;
templateUrl: string;
constructor(clientContext: app.core.IConstants) {
this.bindings = {
textBinding: '#',
dataBinding: '<',
functionBinding: '&'
};
this.controller = TestController;
this.templateUrl = clientContext.baseUrl + "Areas/ng/app/fundraising/donationEntry/components/test1/test1.html";
}
}
// register the controller with app
angular.module(AngularGlobals.donationEntry)
.component("test1", [app.core.AngularGlobals.appCoreConstants, (c) => new test1(c)]);
}
When I run this, I end up with the following error:
angular.js:61 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module donationEntry due to:
TypeError: t.charAt is not a function

This appears to work, though I wouldn't call it the most eloquent of answers. Again, written in Typescript:
namespace donationEntry.Components{
"use strict";
class test1 implements ng.IComponentOptions {
public static id: string = AngularGlobals.donationEntry + ".test1";
bindings: any;
controller: any;
templateUrl: string;
constructor(clientContext: app.core.IConstants) {
this.bindings = {
textBinding: '#',
dataBinding: '<',
functionBinding: '&'
};
this.controller = TestController;
this.templateUrl = clientContext.baseUrl + "Areas/ng/app/fundraising/donationEntry/components/test1/test1.html";
}
}
// register the controller with app
var clientContext = <app.core.IConstants>angular.injector(['ng', app.core.AngularGlobals.appCore]).get(app.core.AngularGlobals.appCoreConstants);
angular.module(AngularGlobals.donationEntry)
.component("test1", new test1(clientContext));
}

I try to stay away from Angular's injection or module mechanism whenever I can, preferring straight ES6.
You can do:
//clientContext.ts
export = { baseUrl: 'whateva' }
And then import like this:
import clientContext from './path/to/clientContext'

Related

Where am I doing wrong in converting angularjs component into es6 class?

The options for chart are not coming. $onChanges method is not getting invoked. There is no compilation error though. I have executed the same without es6 convention. When I have converted this into es6 classes, I am facing this issue. Please help...
class chartController{
constructor(dashboardService){
this.dashboardService = dashboardService;
}
$onChanges(changes) {
console.log(changes);
if (changes && changes.options.currentValue) {
this.lineChartOptions = dashboardService.options.getLineChartOptions();
console.log("calling updateLineChartOptions");
updateLineChartOptions();
}
}
updateLineChartOptions() {
angular.extend(this.lineChartOptions, this.options);
this.lineChartOptions.bindingOptions = {
'dataSource': '$ctrl.options.dataSource',
};
this.lineChartOptions.valueAxis = {
valueType: 'numeric'
};
}
}
class ChartComponent{
bindings = {
$transition$: '<', options: '<'
};
controller = chartController;
templateUrl = 'views/chart.html';
}
app.component('chart', ChartComponent);
const ChartComponent = {
bindings: {
$transition$: '<',
options: '<'
},
controller: chartController,
templateUrl: 'views/chart.html',
}
app.component('chart', ChartComponent);
The .component method of an angular.module instance requires an object for its second argument, not a class (or function).
For more information, see
AngularJS angular.module Type API Reference - component method

Unit test angular 1.x components with Jasmine (using Typescript, Webpack)

I am writing an app using angular 1.6, typescript, webpack, karma and jasmine. I was able to create unit tests for angular services, but now I am having troubles for testing components. On SO(1) and (2) and on the net I found different examples (like this), but not a clear guide explaining how to test angular 1 components with the above technology set.
My component (HeaderComponent.ts):
import {IWeatherforecast} from '../models/weather-forecast';
import WeatherSearchService from '../search/weather-search.service';
import WeatherMapperService from '../common/mapping/weatherMapper.service';
export default class HeaderComponent implements ng.IComponentOptions {
public bindings: any;
public controller: any;
public controllerAs: string = 'vm';
public templateUrl: string;
public transclude: boolean = false;
constructor() {
this.bindings = {
};
this.controller = HeaderComponentController;
this.templateUrl = 'src/header/header.html';
}
}
export class HeaderComponentController {
public searchText:string
private weatherData : IWeatherforecast;
static $inject: Array<string> = ['weatherSearchService',
'$rootScope',
'weatherMapperService'];
constructor(private weatherSearchService: WeatherSearchService,
private $rootScope: ng.IRootScopeService,
private weatherMapperService: WeatherMapperService) {
}
public $onInit = () => {
this.searchText = '';
}
public searchCity = (searchName: string) : void => {
this.weatherSearchService.getWeatherForecast(searchName)
.then((weatherData : ng.IHttpPromiseCallbackArg<IWeatherforecast>) => {
let mappedData = this.weatherMapperService.ConvertSingleWeatherForecastToDto(weatherData.data);
sessionStorage.setItem('currentCityWeather', JSON.stringify(mappedData));
this.$rootScope.$broadcast('weatherDataFetched', mappedData);
})
.catch((error:any) => console.error('An error occurred: ' + JSON.stringify(error)));
}
}
The unit test:
import * as angular from 'angular';
import 'angular-mocks';
import HeaderComponent from '../../../src/header/header.component';
describe('Header Component', () => {
let $compile: ng.ICompileService;
let scope: ng.IRootScopeService;
let element: ng.IAugmentedJQuery;
beforeEach(angular.mock.module('weather'));
beforeEach(angular.mock.inject(function (_$compile_: ng.ICompileService, _$rootScope_: ng.IRootScopeService) {
$compile = _$compile_;
scope = _$rootScope_;
}));
beforeEach(() => {
element = $compile('<header-weather></header-weather>')(scope);
scope.$digest();
});
To me is not clear how to access the controller class, in order to test the component business logic. I tried injecting $componentController, but i keep getting the error "Uncaught TypeError: Cannot set property 'mock' of undefined", I think this is related to angular-mocks not properly injected.
Can anyone suggest an approach of solution or a site where to find further details about unit testing angular 1 components with typescript and webpack?
I was able to found a solution for my question. I post the edited code below, so others can benefit from it and compare the starting point (the question above) with the final code for the unit test(below, splitted in sections for the sake of explanation).
Test the component template :
import * as angular from 'angular';
import 'angular-mocks/angular-mocks';
import weatherModule from '../../../src/app/app.module';
import HeaderComponent, { HeaderComponentController } from '../../../src/header/header.component';
import WeatherSearchService from '../../../src/search/weather-search.service';
import WeatherMapper from '../../../src/common/mapping/weatherMapper.service';
describe('Header Component', () => {
let $rootScope: ng.IRootScopeService;
let compiledElement: any;
beforeEach(angular.mock.module(weatherModule));
beforeEach(angular.mock.module('templates'));
beforeEach(angular.mock.inject(($compile: ng.ICompileService,
_$rootScope_: ng.IRootScopeService) => {
$rootScope = _$rootScope_.$new();
let element = angular.element('<header-weather></header-weather>');
compiledElement = $compile(element)($rootScope)[0];
$rootScope.$digest();
}));
As for directives, also for components we need to compile the relative template and trigger a digest loop.
After this step, we can test the generated template code:
describe('WHEN the template is compiled', () => {
it('THEN the info label text should be displayed.', () => {
expect(compiledElement).toBeDefined();
let expectedLabelText = 'Here the text you want to test';
let targetLabel = angular.element(compiledElement.querySelector('.label-test'));
expect(targetLabel).toBeDefined();
expect(targetLabel.text()).toBe(expectedLabelText);
});
});
Test the component controller :
I created two mocked objects with jasmine.createSpyObj. In this way it is possible to create an instance of our controller and pass the mocked objects with the desired methods.
As the mocked method in my case was returning a promise, we need to use the callFake method from the jasmine.SpyAnd namespace and return a resolved promise.
describe('WHEN searchCity function is called', () => {
let searchMock: any;
let mapperMock: any;
let mockedExternalWeatherData: any;
beforeEach(() => {
searchMock = jasmine.createSpyObj('SearchServiceMock', ['getWeatherForecast']);
mapperMock = jasmine.createSpyObj('WeatherMapperMock', ['convertSingleWeatherForecastToDto']);
mockedExternalWeatherData = {}; //Here I pass a mocked POCO entity (removed for sake of clarity)
});
it('WITH proper city name THEN the search method should be invoked.', angular.mock.inject((_$q_: any) => {
//Arrange
let $q = _$q_;
let citySearchString = 'Roma';
searchMock.getWeatherForecast.and.callFake(() => $q.when(mockedExternalWeatherData));
mapperMock.convertSingleWeatherForecastToDto.and.callFake(() => $q.when(mockedExternalWeatherData));
let headerCtrl = new HeaderComponentController(searchMock, $rootScope, mapperMock);
//Act
headerCtrl.searchCity(citySearchString);
//Assert
expect(searchMock.getWeatherForecast).toHaveBeenCalledWith(citySearchString);
}));
});
});
Thanks for this post! I worked at the same time at the same problem and also found a solution. But this hero example doesn't require compiling the component (also no digest required) but uses the $componentController where also bindings can be defined.
The my-components module - my-components.module.ts:
import {IModule, module, ILogService} from 'angular';
import 'angular-material';
export let myComponents: IModule = module('my-components', ['ngMaterial']);
myComponents.run(function ($log: ILogService) {
'ngInject';
$log.debug('[my-components] module');
});
The hero component - my-hero.component.ts
import {myComponents} from './my-components.module';
import IController = angular.IController;
export default class MyHeroController implements IController {
public hero: string;
constructor() {
'ngInject';
}
}
myComponents.component('hero', {
template: `<span>Hero: {{$ctrl.hero}}</span>`,
controller: MyHeroController,
bindings: {
hero: '='
}
});
The hero spec file - my-hero.component.spec.ts
import MyHeroController from './my-hero.component';
import * as angular from 'angular';
import 'angular-mocks';
describe('Hero', function() {
let $componentController: any;
let createController: Function;
beforeEach(function() {
angular.mock.module('my-components');
angular.mock.inject(function(_$componentController_: any) {
$componentController = _$componentController_;
});
});
it('should expose a hero object', function() {
let bindings: any = {hero: 'Wolverine'};
let ctrl: any = $componentController('hero', null, bindings);
expect(ctrl.hero).toBe('Wolverine');
})
});
Note: It took some time to fix an error in testing the binding:
$compileProvider doesn't have method 'preAssignBindingsEnabled'
The reason was a version difference between angular and angular-mock. The solution was provide by: Ng-mock: $compileProvider doesn't have method 'preAssignBindingsEnabled`

Angular + Typescript code convention

I am using a combination of Angularjs + Typescript for my project. I am searching for a good code convention. There are some some good examples for the two technologies separately. For example I follow this one when using TypeScript:
https://github.com/Platypi/style_typescript#introduction
But couldn't find a good one for the combination of Angularjs + Typescript. To be a little bit more specific, for example, I need a convention on how to write directives with the typescript syntax etc.
I could not find any good articles on the topic. If someone can share something on the topic it will be great. Thanks!
I have followed this projects structure when writing angularjs + typescript.
Since directives are actually factory functions writing directives will be done in the same way:
module Directives{
export function MyDirective(optionalService): ng.IDirective{
var myDirective = {};
myDirective.restrict = 'A';
myDirective.link = function(scope, elem){};
//etc
return myDirective;
}
MyDirective.$inject = ["optionalService"];
}
app.directive("myDirective", Directives.MyDirective);
If you use Angular1.5+ you can follow Angular2 Component style:
class DemoController implements ng.IComponentController {
public static $inject = [
'Service1',
];
constructor(private Service1: IService1) {
//
}
public $onInit(): void {
// ---
}
public $postLink(): void {
// ---
}
// ---
}
export const DemoComponent = {
selector: 'demoComponent',
bindings: {
prop1: '<',
prop2: '<',
},
controller: DemoController,
templateUrl: require('./your-tpl.html'),
};
And somewhere in your module, you can register this component:
.component(DemoComponent.selector, DemoComponent)
For creating directives this code style is also pretty nice:
export class MyDemoDirective implements ng.IDirective {
public restrict: string;
public static $inject: string[] = [
'Service1',
'Service2',
];
constructor(private Service1: IService1, private Service2: IService2) {
this.restrict = 'A';
// ---
}
public link(...) {
// ---
}
public static factory(): ng.IDirectiveFactory {
const directive = (Service1: IService1, Service2: IService2) => {
return new MyDemoDirective($filter, User);
};
return directive;
}
}

Directive with Typescript and isolate scope function binding

I am writing a web app with AngularJS and, for the first time, using TypeScript. The issue I'm having is with a directive executing a function passed on its isolate scope.
I have a controller that is managing "work" of different types. I then have different directives to manage each type of work. The controller reserves the next piece of work, then places it on the scope for the appropriate directive. The controller is below.
module app.work {
interface IWorkScope {
workDone: boolean;
workCompleted(): void;
}
export class WorkController implements IWorkScope {
currentReservedWork: app.work.IReservedWork;
static $inject = ['app.work.WorkService', '$log'];
constructor(private workService: app.work.IWorkService,
private $log: ng.ILogService) {
}
private getNextWork() {
//...call service, reserve work, prep data...
}
public workCompleted(): void {
//...any cleanup tasks, reserve next piece of work....
}
}
angular.module('app.work')
.controller('app.work.WorkController', WorkController);
}
The directives then handling the actual workflow of executing the "work" of its type. An example is below.
module app.verify {
'use strict';
export interface IVerifyItemScope extends ng.IScope {
reserved: app.work.IReservedWork;
onItemComplete(): any;
saveButtonClicked(): void;
item: app.verify.IVerifyItem;
vm: app.verify.IVerifyItemController;
}
export interface IVerifyItemController {
getVerifyItem(): void;
}
class VerifyItemController implements IVerifyItemController{
item: app.verify.IVerifyItem;
statuses: app.verify.VerifyResultStatus[];
tempBind: number;
static $inject = ['$scope', 'app.verify.VerifyService', '$log'];
constructor(public $scope: IVerifyItemScope,
private verifyService: app.verify.IVerifyService,
private $log: ng.ILogService) {
}
saveButtonClicked(): void {
this.$log.debug('button clicked');
this.$scope.onItemComplete();
}
getVerifyItem(): void {
//...call service to get specific work details...
}
}
angular
.module('app.verify')
.directive('sfVerifyItem', verifyItem);
function verifyItem(): ng.IDirective {
var directive = <ng.IDirective> {
restrict: 'E',
link: link,
templateUrl: '....',
controller: VerifyItemController,
controllerAs: 'vm',
scope: {
reserved: '=',
onItemComplete: '&'
}
};
function link(scope: any, element: ng.IAugmentedJQuery, attributes: any, controller: IVerifyItemController): void {
//...do any prep...
}
return directive;
}
}
<data-sf-verify-item reserved="vm.currentReservedWork" onItemComplete="vm.workCompleted()"></data-sf-verify-item>
When the user compeletes the "work", the directive will do any necessary service calls. Last, it executes function onItemComplete that was passed on the scope to inform the controller that the work is done, then the controller can reserve more work and the process repeats.
The issue I'm having is the function bound on the scope isn't getting executed. I can debug and see it on the isolate scope, but when I execute it in the directive (saveButtonClicked() above), nothing happens in the parent controller.
Sorry for the long post, but any help or insight would be greatly appreciated.
See Hugues comment above, forgot to convert binding from camel case.

Implementing angularjs directives as classes in Typescript

So after taking a look at some of the examples of angularjs directives in typescript, it seems most people agree to use functions instead of classes when implementing them.
I would prefer to have them as a class and attempted to implement them as follows:
module directives
{
export class search implements ng.IDirective
{
public restrict: string;
public templateUrl: string;
constructor()
{
this.restrict = 'AE';
this.templateUrl = 'directives/search.html';
}
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");
}
}
}
Now this works fine. However, I need to have an isolated scope with some attributes and I'm struggling to find out how to include that in the class itself.
logic dictates that since I can have
public restrict: string;
public templateUrl: string;
I should be able to have something like:
public scope;
But I'm not sure if this is correct or how to carry on from there (i.e how to add the attributes to the scope).
Anybody know how to solve this? (hopefully, without having to revert to a function if possible)
Thanks,
Creating directives as classes can be problematic since you still need to involve a factory function to wrap its instantiation. For example:
export class SomeDirective implements ng.IDirective {
public link = () => {
}
constructor() {}
}
What Doesn't Work
myModule.directive('someDirective', SomeDirective);
Since directives are not invoked using 'new' but are just called as factory functions. This will cause problems on what your constructor function actually returns.
What Does (with Caveats)
myModule.directive(() => new SomeDirective());
This works fine provided you don't have any IoC involved, but once you start introducing injectables, you have to maintain duplicate parameter lists for your factory function and your directive contstructor.
export class SomeDirective implements ng.IDirective {
...
constructor(someService: any) {}
}
myModule.directive('someDirective', ['someService', (someService) => new SomeDirective(someService)]);
Still an option if that is what you prefer, but is important to understand how the directive registration is actually consumed.
An alternative approach
The thing that is actually expected by angular is a directive factory function, so something like:
export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return {
link: () => {...}
};
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations
myModule.directive('someDirective', SomeDirectiveFactory);
This has the benefit of allowing the use of $inject annotations since angular needs it to be on the factory function in this case.
You could always return an instance of your class from the factory function as well:
export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return new SomeDirective(someService);
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations
But really depends on your use case, how much duplication of parameter lists you are okay with, etc.
Assuming that what you have works without an islolated scope, the following should work with an isolated scope:
module directives
{
export class search implements ng.IDirective
{
public restrict = 'AE';
public templateUrl = 'directives/search.html';
public scope = {
foo:'=',
bar:'#',
bas:'&'
};
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");
}
}
}
Here is my proposal:
Directive:
import {directive} from '../../decorators/directive';
#directive('$location', '$rootScope')
export class StoryBoxDirective implements ng.IDirective {
public templateUrl:string = 'src/module/story/view/story-box.html';
public restrict:string = 'EA';
public scope:Object = {
story: '='
};
public link:Function = (scope:ng.IScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes):void => {
// console.info(scope, element, attrs, this.$location);
scope.$watch('test', () => {
return null;
});
};
constructor(private $location:ng.ILocationService, private $rootScope:ng.IScope) {
// console.log('Dependency injection', $location, $rootScope);
}
}
Module (registers directive...):
import {App} from '../../App';
import {StoryBoxDirective} from './../story/StoryBoxDirective';
import {StoryService} from './../story/StoryService';
const module:ng.IModule = App.module('app.story', []);
module.service('storyService', StoryService);
module.directive('storyBox', <any>StoryBoxDirective);
Decorator (adds inject and produce directive object):
export function directive(...values:string[]):any {
return (target:Function) => {
const directive:Function = (...args:any[]):Object => {
return ((classConstructor:Function, args:any[], ctor:any):Object => {
ctor.prototype = classConstructor.prototype;
const child:Object = new ctor;
const result:Object = classConstructor.apply(child, args);
return typeof result === 'object' ? result : child;
})(target, args, () => {
return null;
});
};
directive.$inject = values;
return directive;
};
}
I thinking about moving module.directive(...), module.service(...) to classes files e.g. StoryBoxDirective.ts but didn't make decision and refactor yet ;)
You can check full working example here: https://github.com/b091/ts-skeleton
Directive is here: https://github.com/b091/ts-skeleton/blob/master/src/module/story/StoryBoxDirective.ts
Here finally i got working a directive as class plus inheritance. In derived directive I extend the scope plus define the templateUrl.
You can override any methods from base directive
.
The key was to return from constructor the instance of directive.Angularjs calls constructor without new keyword. In this case this is of type window
I wrapped few lines to check the instance type of this and in case of window I create a new instance of directive. (See Activator class from sample below)
module Realty.directives {
export class BaseElementWithLabel implements ng.IDirective {
public restrict = 'E';
public replace = true;
public scope = {
label: '#',
model: '=',
icon: '#',
readonlyElement: '=',
remark: '#'
}
constructor(extendedScope) {
if (!(this instanceof Window)) {
extendedScope = extendedScope || {};
this.scope = angular.extend(this.scope, extendedScope);
}
}
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes, controller, transclude) {
scope['vm'] = {};
}
}
}
module Realty.directives {
export class textareaWithLabel extends Realty.directives.BaseElementWithLabel implements ng.IDirective {
templateUrl = 'directives/element-form/textarea-with-label-template.html';
constructor() {
super({
rows: '#'
});
return Realty.Activator.Activate(this, textareaWithLabel, arguments);
}
};
};
module Realty {
export class Activator {
public static Activate(instance: any, type, arguments) {
if (instance instanceof type) {
return instance;
}
return new(type.bind.apply(type, Array.prototype.concat.apply([null], arguments)));
}
}
}

Resources