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

前端 未结 1 1522
青春惊慌失措
青春惊慌失措 2021-01-24 02:44

Should it be associated with the app module? Should it be a component or just a controller? Basically what I am trying to achieve is a common layout across all pages within whic

1条回答
  •  不知归路
    2021-01-24 03:13

    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.template.html:

    
    
    
    

    This way, every component injected inside 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 : ''
    })
    

    which will effectively route and load your component inside

    New versions of ui-router include component routing.

    0 讨论(0)
提交回复
热议问题