I'm using Angular 1.5+ with Typescript, preparing my code to be compatible with Angular 2. I've got a situation where many of my components need to use an application-wide repository location for the views that are mapped to their templateUrl properties, but sometimes a view needs a specific, local implementation.
So, normally the views are hosted on a fast-served CDN, they're re-used between multiple sites that all belong to the same general code base, api, etc. This is done to prevent duplicating them and to centralize what doesn't need to be repeated.
Rarely, I'll need to override this behavior and use a more specific, fine-tuned view. So my approach to this was to add a binding to the components called viewLocation, with the intent to use it like this;
<component-name></component-name> is the default. In this situation, the default CDN path is used.
<component-name view-location="local"></component-name> is a unique situation. If this happens, the templateUrl should be able to respond to that and switch to a path relative to the specific application and not from the CDN.
I thought it would be pretty simple until I realized that I wouldn't have access to the binding properties within the actual constructor or templateUrl function, as is demonstrated here;
export class SidebarComponent extends Component {
constructor() {
super();
this.bindings = { viewLocation: '=' };
// other properties
this.templateUrl = ($someService: IServiceInterface): string => {
// help! I don't have access to the viewLocation property!
}
}
}
So is there anything else I can do to get access to that property?
This is not done in TS, but the AngularJS 1.5 component generally provides the $element and $attrs to the $injector when you are using an injectable template.
This is an example in AngularJS using Javascript where the template URL is picked based on an attribute set on the component:
angular.module('example', []);
angular.module('example').component('myComponent', {
templateUrl: function($element, $attrs, $log) {
$log.info('determining template to be used');
if($attrs.useTemplate) {
return $attrs.useTemplate;
}
return 'default.html';
}
});
Template snippet:
<my-component use-template="hui.html"></my-component>
<my-component use-template="bu.html"></my-component>
<p></p>
<my-component></my-component>
Working example:
template injection in an angular 1.5 component
Related
In Angular JS I would want to get a component controller instance manually, that ideally is achieved through the require binding in component. I have a requirement where in I am outside the Angular JS component environment and I cannot use require.
// Sample require binding
module.component('superHeros', {
template: `
<h2>
Super Heros Component
</h2>
`,
require: {
parentCtrl: '^heroList'
},
controller: superHerosControler
});
Though I thought this could be achieved with $injector of angular but does not seem to work (throws Unknown provider).
So I want to do this
require: {
parentCtrl: '^heroList'
}
like this this.requiredController = $injector.get(<componentName>);
I understand that this works perfectly for Services or factories. Is there a way to achieve this or a workaround that can essentially get me an component controller instance ?
Plunker here
Any help would be appreciated. Thanks
I have troubles with ui-router and angularjs scope after changing state - new created scope uses old controller (or vise versa).
I use AngularJS "angular": "1.5.8", and ui-router "#uirouter/angularjs": "^1.0.22", components written in ES6 style as classes.
Component example:
import template from './my-container.html';
export const MyContainer = {
bindings: {
},
template: template,
controller: class {
constructor($scope) {
'ngInject';
this.$scope = $scope;
...
Route/State definition:
.state('mystate', {
url: '/mystate',
component: 'myPage' // in myPage <my-container>
})
Problem:
On first page load everything works correctly. But when I change state and go back - any changes don't appear in template.
I mentioned that $scope.$id was changed but my controller still use previous scope object.
For debugging I added two console prints: inside onInit and myUpdateData functions.
On first screenshot we can see correct ids (init, update func, from template/dom element):
And after changing states (wrong behavior):
future calls updateData - it uses old (14 on scr) scope but rendered new one. So we don't see any changes in template.
Any ideas how to find out from this situation?
Solved.
Issue was in components code - I forgot to remove all references on previous controller instance and after changing state this controller left alive in memory (I'm not sure how it has been connected to new scope object but it describes solution).
When you got behavior like this - try to leave almost empty component and you will find bug.
I am unable to inject resolve property of ui-routing in controller.
It is giving
Error: $injector:unpr
Unknown Provider
When I'm using controller property in state definition object as following
.state('widget', {
url: '/widgets',
template: '<h1>{{name}}</h1>',
controller: function(widget, $scope) {
$scope.name = widget.name;
},
resolve: {
// standard resolve value promise definition
widget: function() {
return {
name: 'myWidget'
};
},
// resolve promise injects sibling promise
features: function(widget) {
return ['featureA', 'featureB'].map(function(feature) {
return widget.name+':'+feature;
});
}
}
});
Then it is working fine and I'm able to get the widget in controller and able to use in html.
Please see the fiddle for code.
http://jsfiddle.net/sunilmadaan07/ugsx6c1w/8/
Might be I'm making a silly mistake.
Before posting this question I have tried returning with simple object, promise object to the property.
Thanks In Advance.
You can not get resolved data in the directive with the code you did. Basically, you are trying to implement component based structure with an older version of angular 1.3.x.
You have two options to achieve this.
Create route controller then you can access resolve to the controller as local dependency then use that dependency as binding to the directive.
Here is example - http://plnkr.co/edit/TOPMLUXc7GhXTeYL0IFj?p=preview
Upgrade angular version to 1.5.x and use "ui-router-route-to-components": "^0.1.0"
Here working example of your code - http://jsfiddle.net/ugsx6c1w/25/
In order for the controller to be able to use resolvers, it should be route component (only in UI Router 1.x) or route controller.
widget and features are local dependencies, they aren't registered in the injector and aren't available anywhere in the application except route controller/component.
As explained here, resolvers can be passed to nested components in UI Router 0.3.x and injected directly to route components in 1.x.
I'm just learning Angular and have a very basic app set up. When rendering some data via the templateUrl property of a route, what would be the best way to include a sub-controller in the returned template? For example, including a "createOrEditItem" template at the bottom of a "viewItem" template so that the "createOrEditItem" can be reused on its own later?
I've tried putting a div in the template with its ng-controller attribute set to a controller name that I've defined at the app level, but it's not being activated. Should this be done with a directive instead to make it instantiate when the master controller has its contents set, or am I missing something more fundamental?
yes, as mentioned in the later part of the question, you should be using a directive. Or, if using AngularJS >= v1.5, component should be the choice because they are pluggable and works well with nesting too.
Note that for the route also, you can directly use a component like this:
var myMod = angular.module('myMod', ['ngRoute']);
myMod.component('home', {
template: '<h1>Home</h1><p>Hello, {{ $ctrl.user.name }} !</p>',
// ^^^^ other components can be used here
controller: function() {
this.user = {name: 'world'};
}
});
myMod.config(function($routeProvider) {
$routeProvider.when('/', {
template: '<home></home>'
});
});
Now, as the comment suggests, you can freely use other components in the template of home component.
Hope this helps a bit!
A directive can be used.
Another option is to use a seperate view/route. So when you add a ui-view tag, you could define your view and route.
This is explained here:
https://scotch.io/tutorials/angular-routing-using-ui-router
I am developing an Angular application. I need to add special behavior to all links. In AngularJS would just write a directive like this:
angular.module('whatever.module', []).directive('href', function() {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
// do stuff
}
};
});
In Angular I can write a directive like this:
#Directive({
selector: '[href]',
})
export class MyHrefDirective {
constructor() {
// whatever
}
}
But how can I tell the application to use that directive globally? I have a ton of views with links on them. Do I have to import it and specify it in the directives array in every of those components (which is A LOT)?
I tried injecting it to the bootstrap function like you're supposed to do with services to have one instance globally but that didn't work
My understanding is that you have to opt in to all custom directives at the component level. Only PLATFORM_DIRECTIVES are implicitly included (ngFor, ngIf etc.).
However, you can register your own custom directive as a PLATFORM_DIRECTIVE
import { provide, PLATFORM_DIRECTIVES } from '#angular/core';
bootstrap(RootCmp, [
provide(PLATFORM_DIRECTIVES, {useValue: YourCustomDirective, multi: true}),
]);
Here is an article that talks more about the process:
http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html
EDIT:
I consider this less of a concern now since components are declared at the module level. This means a lot less repetition since you no longer have to declare child components at the individual component level.