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

僤鯓⒐⒋嵵緔 提交于 2019-12-02 06:27:17

This might be a bit subjective to answer but what I personally do in a components based Angular application is to create a component that will encapsulate all the other components.

I find it particularly useful to share login information without needing to call a service in every single component. (and without needing to store user data inside the rootScope, browser storage or cookies.

For example you make a component parent like 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 will take care of the 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> will be able to 'inherit' the master component like so:

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

and in the component controller

var vm=this;
this.user = {};
this.$onInit = function() {
    vm.user = vm.master.getUser();
};

You need to use the life cycle hook $onInit to make sure all the controllers and bindings have registered.

A last trick to navigate between components is to have a route like so (assuming you use ui-router stable version):

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

which will effectively route and load your component inside <ui-view>

New versions of ui-router include component routing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!