angular 1.5 components and es6 modules - angularjs

I am new to angular and I am trying to use the new component helper in angular 1.5.
My index.html file looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Github Invoicing</title>
<link rel="icon" type="image/x-icon" href="/img/favicon.ico">
<base href="/">
</head>
<body ng-app="app">
<div ng-controller="mainCtrl as ctrl">
<log-in/>
</div>
</body>
</html>
My app.js file looks like this:
import angular from 'angular';
import logIn from './components/logIn';
angular.module('app', [])
.controller('mainCtrl', function() {
});
My logIn.js file looks like this
import angular from 'angular';
angular.module('app')
.component('logIn', {
template: function($element, $attrs) {
return [
'<div>Content</div>'
].join('');
}
});
I get the following error
Uncaught Error: [$injector:nomod] Module 'app' is not available! You
either misspelled the module name or forgot to load it. If registering
a module ensure that you specify the dependencies as the second
argument.
This is obviously because the app has not been created when the import statement for logIn.js executes from app.js runs.
If this was react or ember, I would be exporting the component somehow but as I'm new to angular, I don't really know what to do.
The only way I can get this to work is define logIn.js like this:
import angular from 'angular';
const logIn = {
template: function($element, $attrs) {
return [
'<div>Content</div>'
].join('');
}
};
export default logIn;
And then create the component in app.js:
import angular from 'angular';
import logIn from './components/logIn';
angular.module('app', [])
.controller('mainCtrl', function() {
}).component('logIn', logIn);
This feels wrong.

you can create another module e.x. component
import angular from 'angular'
angular.module('component',[])
.component('logIn', {
template: function($element, $attrs) {
return [
'<div>Content</div>'
].join('');
}
});
and your app will be depended on this module
import angular from 'angular';
import logIn from './components/logIn';
angular.module('app', ['component'])
.controller('mainCtrl', function() {
});

Related

use Angular routing in AngularJS/Angular hybrid app reload all page

I am trying to make Angular routing in my AngularJS/Angular hybrid application.
I created app-routing.module.ts file :
import { ModuleWithProviders } from "#angular/core";
import { Routes, RouterModule, ExtraOptions } from '#angular/router';
import {SignInComponent} from "./modules/login/components/sign-in/sign-in.component";
import {ActivationComponent} from "./modules/login/components/activation/activation.component";
const routes: Routes = [
{
path: 'sign-in',
component: SignInComponent
},
{
path: 'activation',
component: ActivationComponent
},
{
path: '',
pathMatch: 'full',
redirectTo: '/activation'
},
{
path: '**',
pathMatch: 'full',
redirectTo: '/activation'
}
];
export const routingModule: ModuleWithProviders = RouterModule.forRoot(routes);
in app.module.ts I added routingModule to "imports" array and in app.component.html I added :
<button (click)="goto('sign-in')">go to home</button>
<button (click)="goto('activation')">go to product</button>
<router-outlet></router-outlet>
When insight by index.html i am using just Angular it works perfectly
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
But when I am adding my AngularJS code just adding
this.upgrade.bootstrap(document.body, ['app']);
my current Angular routing instead reload content of "router-outlet" tag, reloads completely the page. If I remove
this.upgrade.bootstrap(document.body, ['app']);
it works fine.
Does anybody had some similar issues and maybe someone can propose some scenario how to make Angular routing work appropriately insight hybrid AngularJS/Angular application?
Thanks
It looks like you have not configured the AngularJS and Angular Router in the correct way, please verify the below steps-
Default route (.otherwise) should be removed from AngularJS routing.
Implement the 'UrlHandlingStrategy' interface as a part of Angular router config settings to handle the routing for specific URLs. This will avoid the Angular router conflict with AngularJS router-
export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url: UrlTree): boolean {
return url.toString().startsWith('/ng/');
}
extract(url: UrlTree): UrlTree { return url; }
merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree { return newUrlPart; }
}
Add above class (Ng1Ng2UrlHandlingStrategy) as a provider in the root module for URL handling strategy-
providers: [
{ provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy }
]
Add both AngularJS and Angular outlet/directive in the app component html
<router-outlet></router-outlet>
<div class="ng-view"></div>
Hash based routing will work but setUpLocationSync(upgrade) is required to support the html 5 based routing in the hybrid app. Please update the main.ts file like below-
upgrade.bootstrap(document.body, ['app']);
setUpLocationSync(upgrade);

Downgrade angular2 component written with Typescript. How to import it into angular 1 project written with es5?

I have downgrade a component written in Angular2 + Typescript. Now I want to use it in simple angular 1 app, But the js file compiled from Typescript is using 'import' and I get from browser it is not supported. What I have missed?
This is a simple angular 2 componenet:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'hello-world',
template: `
<p>
hello from angular 2!
</p>
`,
styles: []
})
export class HelloWorldComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
import * as angular from 'angular';
import { downgradeComponent } from '#angular/upgrade/static';
angular.module('dannyApp', [])
.directive(
'helloWorld',
downgradeComponent({component: HelloWorldComponent}) as angular.IDirectiveFactory
);
This is the simple angular1 app tring to use this angular 2 component above:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="dist\out-tsc\app\hello-world\hello-world.component.js"></script>
<script>
angular.module('app', [])
.controller('FrameController', ['$injector', function($injector) {
var vm = this;
vm.message = 'Hello from angular 1';
}]);
</script>
<title>Title</title>
</head>
<body ng-app="app">
<div id="body">
<div ng-controller="FrameController as vm">
{{vm.message}}
</div>
<!-- the angular 2 componenet -->
<hello-world></hello-world>
</div>
</body>
</html>
The browser error:
Uncaught SyntaxError: Unexpected token import
on the line:
import { Component } from '#angular/core';
Make sure you have compiled your Typescript component to ES5.
Your code looks like ES6/Typescript.
Check your tsconfig.json and make sure target: "es5".

using components in anuglar-ui

I'm making an angular 1 application with typescript and components. But my views arn't loaded.
and I can't seem to figure out why, the ui-router is working and my components are loading as wel if I include them in my index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular typescript webpack</title>
</head>
<body ng-cloak>
<a ui-sref="app.home" ui-sref-active="active">Hello</a>
<a ui-sref="app.about" ui-sref-active="active">About</a>
<messages-application></messages-application>
</body>
</html>
app.ts
import './modules/_application/index';
import './modules/about/index';
import 'angular';
angular.module('app', [ 'app.application', 'app.about']);
angular.bootstrap(document, ['app'], {
strictDi: true
});
modules/_application/index.ts
import 'angular';
import 'angular-ui-router';
import {config as routesConfig} from './configs/routes';
import {MessagesApplicationComponent} from './components/messagesApplication/MessagesApplicationComponent';
angular.module('app.application', ['ui.router'])
.component('messagesApplication', new MessagesApplicationComponent())
.config(routesConfig);
modules/_application/configs/routes.ts
config.$inject = ['$stateProvider'];
export function config($stateProvider: ng.ui.IStateProvider): void {
let abstractState: ng.ui.IState = {
abstract: true,
name: 'app',
component: 'messages-application'
};
$stateProvider.state(abstractState);
}
modules/_application/components/messagesApplication/messagesApplicationComponent.ts
export class MessagesApplicationComponent implements ng.IComponentOptions {
template: string = `
<h1>Messages application</h1>
<div ui-view></div>
<h3>test</h3>`;
}
and then i have a route for my about
modules/about/index.ts
import 'angular';
import 'angular-ui-router';
import {PageAboutComponent} from './components/pageAbout/PageAboutComponent';
import {config as routesConfig} from './configs/routes';
angular.module('app.about', ['ui.router'])
.component('pageAbout', new PageAboutComponent())
.config(routesConfig);
modules/about/configs/routes.ts
config.$inject = ['$stateProvider'];
export function config($stateProvider: ng.ui.IStateProvider): void {
let aboutState: ng.ui.IState = {
name: 'app.about',
url: '/about',
component: 'page-about',
parent: 'app'
};
$stateProvider.state(aboutState);
}
modules/about/components/pageAbout/pageAboutComponent.ts
export class PageAboutComponent implements ng.IComponentOptions {
public template: string = `
<div>
<ul>
<li>Typescript</li>
<li>Webpack</li>
<li>Angular 1.4</li>
<li>Karma</li>
<li>Jasmine</li>
<li>Istanbul coverage</li>
</ul>
</div>`;
}
anybody knows what I might be forgetting or doing wrong?

Dependencies in AngularJS App Level Module necessary or automatable?

I started a project form the Angular Seed Project. I've done a few Angular projects before, but this is the first one I have setup from scratch. I don't remember having to add new modules to the "app level module" before. Seems like there is a way to automate this, but my Google-Fu is failing me.
Basically, I'm looking for a way to remove 'myApp.home' and such from app.js so that I don't have to always add new pages to the app.js. I know some modules will need to go there, but adding every page there seems like a pain. I already figured out how to automate adding the script references to index.html
//////////////////// APP.JS ////////////////////
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.home'
])
.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({ redirectTo: '/home' });
}]);
//////////////////// HOME.JS ////////////////////
'use strict';
angular.module('myApp.home', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: '../app/home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', [function () {
}]);
<!---------- INDEX.HTML ---------->
<html>
<head>
<title>My App</title>
</head>
<body>
<h1>My App</h1>
<div ng-view></div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="home/home.js"></script>
</body>
</html>
<!---------- HOME.HTML ---------->
<div>TEST</div>
if you will not create a new module for each new page, but use myApp module, then you do not need to add it as dependency to the myApp module. Each page will have its own JS file:
//////////////////// HOME.JS ////////////////////
'use strict';
angular.module('myApp')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: '../app/home/home.html',
controller: 'HomeCtrl'
}
);
}])
.controller('HomeCtrl', [function () {
}
]);

Angular JS - Cannot load data from multiple modules

I'm having problems when trying to use multiple modules in Angular JS. I cannot use more than 1 module, it seems like Angular doesn't recognize the code. I'm willing to use a tree view + flex grid on an application but the tree doesn't shows up, just the flex grid. I'm pretty sure I'm missing something on moduling but I don't know what... Here is the code:
index.htm
<html ng-app="app">
<script src="js/angular/angular.js"></script>
<script src="js/main.js"></script>
<!-- Flex Grid !-->
<script src="js/flexygrid/controllers/FlexControllers.js"></script>
<script src="js/flexygrid/directives/FlexDirectives.js"></script>
<script src="js/flexygrid/misc/FlexBlock.js"></script>
<!-- Tree !-->
<script src="js/tree/controllers/TreeControllers.js"></script>
<script src="js/tree/directives/TreeDirectives.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
main.js
var app = angular.module('app',['flexyLayout.directives','tree.controller']);
FlexControllers.js
function (angular) {
"use strict";
angular.module('flexyLayout.mediator', ['flexyLayout.block']).
controller('mediatorCtrl', ['$scope', '$element', '$attrs', 'Block', function (scope, element, attrs, Block) {
...
}
FlexDirectives.js
function (angular) {
"use strict";
angular.module('flexyLayout.directives', ['flexyLayout.mediator'])
.directive('flexyLayout', function () {
...
})(angular);
FlexBlock.js
(function (angular) {
"use strict";
angular.module('flexyLayout.block', [])
.provider('Block', function () {
...
}
})(angular);
TreeControllers.js
(function(){
angular.module('tree.controller',['angularTreeview']).controller('TreeCtrl', function($scope){
...
}
})();
TreeDirectives.js
(function(){
angular.module('angularTreeview',[]).directive('treeModel',function($compile){
...
}
})();

Resources