I have a dummy component based application, which has the following components:
- App
-- Page
---- Breadcrumb
What i want is to pass the Page resolve data to the Breadcrumb.
This is how the Page config looks like:
$stateProvider.state('page', {
url: '/page',
component: 'page',
resolve: {
routes: ($stateParams) => {
"ngInject";
return [
{url: "/", name: "Home"},
{url: "/page", name: 'Page'}
];
}
}
})
The Page controller:
class PageController {
constructor($stateParams) {
"ngInject";
this.themeColor = "#ff8fd1";
// When i use static data it's works fine..
//this.routes = [
// {url: "/", name: "Main page"},
// {url: "/page", name: 'Sub page'},
//];
this.routes = $stateParams.routes;
}
}
And this is my Breadcrumb component:
let breadcrumbComponent = {
restrict: 'E',
bindings: {
themeColor: "<",
routes: "<"
},
template,
controller
};
The DOM of the Breadcrumb component:
<breadcrumb theme-color="$ctrl.themeColor" routes="$ctrl.routes"></breadcrumb>
Everytime the routes are undefined when i want to define it from the Page controller resolve method.
How do i wait the data, or bind the Breadcrumb again when the data arrives?
One simple way is to use ngIf directive to render breadcrumb component only when routes are resolved:
<breadcrumb
ng-if="$ctrl.routes"
theme-color="$ctrl.themeColor"
routes="$ctrl.routes"></breadcrumb>
I figured out.
If you're want to pass resolve data to your component, or an other you have to set the resolve data as binding in the parent component as well.
// page.component.js
let pageComponent = {
restrict: 'E',
bindings: {
routes: "<"
},
template,
controller
};
Related
I am new to Angular and UI-Router and I have to work with an Angular codebase. I am having difficulty understanding how the params gets mapped to the url. Specifically how topics get injected as topic in /test?topic&manualMode&advancedMode I cannot seem to find the place where I can log out the intermediate value to see how the url gets constructed.
function StateConfig(
$stateProvider: angular.ui.IStateProvider,
breadcrumbsService: BreadcrumbsService
) {
$stateProvider.state("testHub", {
params: {
topics: null
},
url: "/test?topic&manualMode&advancedMode",
views: {
main: {
template:
'<div class="hubContent"><iot-mqtt-client-config></iot-mqtt-client-config></div>'
},
sidebar: {
controller: HelpControllerTutorial,
controllerAs: "vm",
templateUrl: "pages/mqtt/mqtt-client-help.html"
}
}
});
breadcrumbsService.addConfig("testHub", {
name: (i18n: I18nService) => i18n("text.test"),
parentState: null,
reconstructBreadcrumbPath: true
});
}
This should work for you in app.js:
.state('testHub', {
url: "/test/:topic/:manualMode/:advancedMode", // added for dynamic ID params
})
Then your ui-sref in substances.html will append the ( topic or manualMode or advancedMode ) to the url, and you will be able to access that in your controller in $stateParams
I'm working in a small Angularjs 1.5 project and I'm quite new.
I have to create an object or edit an existing object and the template is the same, the only difference in the logic is the call to an http service for data retrieve in case of update.
I use ngRoute.
How can I do to use the same component for both operations ?
EDIT
JS COMPONENT CODE
angular.
module('editProject').
component('editProject', {
templateUrl: 'app/edit-project/edit-project.template.html',
controller:['$http','$routeParams', function EditProjectController($http,$routeParams) {
var self=this;
$http.get('rest/projects/' + $routeParams.id ).then(function(response) {
console.log(JSON.stringify(response.data));
self.project = response.data;
});
}
]
});
ROUTE CONFIG
angular.
module('myApp').
config(['$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/projects', {
template: '<project-list></project-list>'
}).
when('/projects/:id', {
template: '<project-detail></project-detail>'
}).
when('/projects/edit/:id', {
template: '<edit-project></edit-project>'
}).
when('/projects/new', {
template: '<edit-project></edit-project>'
}).
otherwise('/projects');
}
]);
1. Quick fix
Simple solution would be using a conditional checking if the $routeParams.id param is defined, if so, then it need a request to feed the project informations, otherwise not.
if($routeParams.id){
$http.get('rest/projects/' + $routeParams.id ).then(function(response) {
console.log(JSON.stringify(response.data));
self.project = response.data;
});
}
2. Component Router
Even though the previous solution looks simple and functional, it might not be the best. A propper solution is to use a separate component for each route, but you can reuse the form part of it. Also, assuming that you are building a completelly component-based app you should use ngComponentRoute instead of ngRoute.
.component('app', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [
{path: '/projects', name: 'Projects', component: 'projectList', useAsDefault: true},
{path: '/projects/:id', name: 'Project Detail', component: 'projectDetail' },
{path: '/projects/edit/:id', name: 'Edit Project', component: 'editProject' },
{path: '/projects/new', name: 'New Project', component: 'newProject' }
]
});
Then you can create a project editor component and reuse it on both edit and new project page by just adding <project-editor-form project="{}" on-save="$ctrl.mySave()"></project-editor-form>. For example:
.component('projectEditorForm', {
template:
'Project Name: <input type="text" ng-model="$ctrl.project.name">' +
'<button ng-click="$ctrl.onSaveProject($ctrl.project)">Save</button>',
bindings: {
project: '<',
onSave: '&'
},
controller: function () {
var $ctrl = this;
$ctrl.onSaveProject = function (project) {
// general save logic goes here
// if you want to reuse this too
// then emit the on save for onSave binding
$ctrl.onSave($ctrl.project);
}
},
})
.component('editProject', {
template:
'<project-editor-form project="$ctrl.project" on-save="$ctrl.mySave()">' +
'</project-editor-form>',
bindings: {
project: '<',
onSave: '&'
},
controller: function ($http) {
var $ctrl = this;
// consider using a Service to do such task
// instead of request directly from the controller
$http.get('rest/projects/' + $routeParams.id).then(function(response) {
$ctrl.project = response.data;
});
$ctrl.mySave = function (project) {
// save logic here
}
},
})
3. ngRoute with resolve
Another approach that doesn't deppend on ngComponentRoute, is to use the route resolve property, it's very usefull when using component as route template. You add a resolve property to your route, that would be the project, and bind to your form component.
$routeProvider
.when('/projects/edit/:id', {
template: '<project-editor-form project="$resolve.project"></project-editor-form>',
resolve: {
project: function ($route, $q) {
var id = $route.current.params.id;
// again, consider using a service instead
return $http.get('rest/projects/' + id).then(function (response) {
return response.data;
});
}
}
})
.when('/projects/new', {
template: '<project-editor-form project="$resolve.project"></project-editor-form>',
resolve: {
project: {
id: 0,
name: ''
}
}
})
In my Angular project I have some components which loads in parent component and Angular UI Router state. I send the "fields' variable in Page Component.
index.js
...
angular.
module('generalApp').
config(['$stateProvider',
function config($stateProvider) {
$stateProvider
.state('settings', {
url: '/settings',
component: 'page',
resolve: {
type: function() {
return "form";
},
fields: function() {
return require("./data/settingsFields.json");
}
}
})
}
]);
...
page.component.js
...
angular.
module('page').
component('page', {
bindings: {
type: '#',
fields: '<'
},
template: '...<form-page ng-if="$ctrl.type"></form-page>...',
controller: [function PageController() {
...
}
]
});
...
and formPage.component.js
...
angular.
module('formPage').
component('formPage', {
bindings: {
fields: '<'
},
template: require('./formPage.template.html'),
controller: [function formPageController() {
...
}]
});
...
I can to get "fields" variable in Page Component and I want to get it in nested FormPage Component. What I should do for this?
I am looking to upgrade angular version to 1.5 and trying to figure out how I can do routing in Angular 1.5 Component Routing. Currently, we are doing as following using old angular router:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/PP", {
templateUrl: function (route) {
var path;
var menuID = route.MenuID ;
$.ajax({
type: "POST",
async: false,
url: "./api/MyControllerName/MyControllerMethodName",
contentType: "application/json",
data: angular.toJson({
Action: 'NavigationManager.GetHtmlFilePath',
Data: { MenuID: menuID }
})
}).then(function (data) {
if (data.Success == true) {
var rte = $.parseJSON(data.Data);
path = rte.Route;
}
})
return path;
},
reloadOnSearch: false
})
.otherwise({ redirectTo: "/Home" });
}]);
The $.ajax call goes to server and gets the full path of the html file based on the MenuID from the url. Eventually content from this html file gets placed in ng-view.
All the examples of angular 1.5 component routing I have seen have hard coded path information as shown below:
angular.module('heroes', [])
.component('heroes', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [
{ path: '/', name: 'HeroList', component: 'heroList', useAsDefault: true },
{ path: '/:id', name: 'HeroDetail', component: 'heroDetail' }
]
})
My question is how do I replace the hard coded values with values coming from server just like I am doing with old angular router?
I had the same requirements. I had to set menus based on rights. My application is divided as a component tree. So, on login page, I set route registry as below:
class appOptions implements ng.IComponentOptions {
public controller: any;
public template: string;
public $routeConfig: any;
constructor() {
this.$routeConfig = [
{ path: '/', name: 'Login', component: 'login', useAsDefault: true },
{ path: '/workspace/...', name: 'Workspace', component: 'workspace' }
];
this.controller = appCtrl;
this.template = '<ng-outlet></ng-outlet>';
}
}
When user clicks on login button, I will get roles of users if authentication is passed. With successful authentication, server will pass JSON which will have list of permissions. Using that object to create routes. Calling below method in Login page
setRoute() {
this.myRoutes= this.routeService.getRoutes();
this.myRoutes.forEach((route) => {
this.$router.registry.config('workspace', route.route);
});
this.$router.navigate(['Workspace']);
}
routeService is the service which will actually generate routes
Now define interface based on parameter which are using for routing(eg:path, name, component, useAsDefault)
export interface IMyRoutes {
path: string;
name: string;
component: string;
useAsDefault: boolean
}
In controller of service:
public workspaceRoutes: app.IMyRoutes [] = []
getRoutes() {
this.accessProfile = this.userService.GetProfile();//This will get list of permission along with other details from server
if (this.accessProfile != null && this.accessProfile.Permissions.length > 0) {
this.accessProfile.Permissions.forEach((permission) => {
switch (permission) {
case "CanAccessMenu_1":
this.workspaceRoute = {
path: '/another_node_of_tree/...', name: 'Menu1', component: 'menu1', useAsDefault: (this.accessProfile.Role.toLowerCase() == "Role1")
}
this.workspaceRoutes.push(this.workspaceRoute);
break;
case "CanAccessMenu_2":
this.workspaceRoute = {
path: '/some_path/', name: 'Menu2', component: 'menu2', useAsDefault: (this.accessProfile.Role.toLowerCase() == "Role2")
}
this.workspaceRoutes.push(this.workspaceRoute);
break;
case "CanAccessMenu_3":
this.workspaceRoute = {
path: '/another_node_of_tree/...', name: 'Menu3', component: 'menu3', useAsDefault: (this.accessProfile.Role.toLowerCase() == "Role3")
}
this.workspaceRoutes.push(this.workspaceRoute);
break;
}
});
}
return this.workspaceRoutes;
}
I'm currently working on an app where I have multiple nested views, they sort of look like this:
- ui-view
- ui-view="header"
- ui-view="nav"
- ui-view="body"
My states are defined as follows:
.state('index', {
url: '', // default route
templateUrl: 'welcome.html'
})
.state('app', {
abstract: true,
templateUrl: 'app.template.html' // This template contains the 3 different ui-views
})
// I'm using a different state here so I can set the navigation and header by default
.state('in-app', {
parent: 'app',
abstract: true,
views: {
'nav#app': { '...' },
'header#app': { '...' }
}
})
// In-app routes
.state('dashboard', {
parent: 'in-app',
url: '/app/dashboard'
views: {
'body#app': { '...' }
}
})
.state('users', {
parent: 'in-app',
url: '/app/users'
views: {
'body#app': { '...' }
}
})
.state('settings', {
parent: 'in-app',
url: '/app/settings'
views: {
'body#app': { '...' }
}
})
At the moment this works great, but for the in-app routes I would like to define a title that is displayed in the header#app view.
What would be the best way to do this? At the moment I can only think of either setting a variable on the $rootScope, or sending out an event. But for both of those I would need a controller.
Is there a way I could do this directly from my routes config?
The sample applicaiton of the UI-Router, uses this code:
ui-router / sample / app / app.js
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
And that means, that with data : {} feature:
Attach Custom Data to State Objects
You can attach custom data to the state object (we recommend using a data property to avoid conflicts).
// Example shows an object-based state and a string-based state
var contacts = {
name: 'contacts',
templateUrl: 'contacts.html',
data: {
customData1: 5,
customData2: "blue"
}
}
we can do this:
.state('in-app', {
parent: 'app',
abstract: true,
views: {
'nav#app': { '...' },
'header#app': { '...' }
}
data: { title : "my title" },
})
And use it in some template like:
<div>{{$state.current.data.title}}</div>
Some summary.
We can place state and params into $rootScope, so we can access it without any controller anyhwere.
We can declare some more custom stuff via data and use it as a title ... anyhwere