Where should I place code to be used across components/controllers for an AngularJS app? -


should associated app module? should component or controller? trying achieve common layout across pages within can place or remove other components.

here app's structure looks like:

-/bower_components -/core -/login     --login.component.js     --login.module.js     --login.template.html -/register     --register.component.js     --register.module.js     --register.template.html -app.css -app.module.js -index.html 

this might bit subjective answer in components based angular application create component encapsulate other components.

i find particularly useful share login information without needing call service in every single component. (and without needing store user data inside rootscope, browser storage or cookies.

for example make component parent so:

var master = {     bindings: {},     controller: mastercontroller,     templateurl: 'components/master/master.template.html' };  function mastercontroller(loginservice) {      var vm = this;     this.loggeduser = {};      loginservice.getuser().then(function(data) {         vm.loggeduser = data;     });      this.getuser = function() {         return this.loggeduser;     }; }  angular     .module('app')     .component('master', master)     .controller('mastercontroller', mastercontroller); 

the master component take care of routing.

index.html:

<master></master> 

master.template.html:

<your common header> <data ui-view></data> <your common footer> 

this way, every component injected inside <ui-view> able 'inherit' master component so:

var login = {     bindings: {},     require: {         master: '^^master'     },     controller: logincontroller,     templateurl: 'components/login/login.template.html' }; 

and in component controller

var vm=this; this.user = {}; this.$oninit = function() {     vm.user = vm.master.getuser(); }; 

you need use life cycle hook $oninit make sure controllers , bindings have registered.

a last trick navigate between components have route (assuming use ui-router stable version):

.state('home', {     url : '/home',     template : '<home></home>' }) 

which route , load component inside <ui-view>

new versions of ui-router include component routing.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -