Coder Social home page Coder Social logo

Comments (22)

feelepxyz avatar feelepxyz commented on May 31, 2024

We try and load all our data in route resolvers and pass it to directives using attributes. Downside is that you end up passing the data around a lot, upside that the view only renders when all the data is there.
I would probably load stuff in a directive controller if it doesn't affect the current view.

Still think data loading is a bit of pain in Angular apps. Loading data very close to where it's used makes things easier to move about and change (i.e. in controllers), but makes it really hard to rebuild the same app state consistently as it's built up all over the shop. Keeping it central (in a resolve) makes it easier to rebuild a consistent state but then forces you to pass stuff around loads which makes stuff harder to change.

Quite keen on figuring out a better way. The React/ClojureScript framework om has some pretty neat ideas around global app state. But haven't explored this in detail.

from angularjs-style-guide.

hkjels avatar hkjels commented on May 31, 2024

Indeed. I prefer reagent over angular any day, but I'm kind of locked in at this point and have to make the best of it.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

How do you manage (for example) currentUser state - authentificated or not? I'm trying to follow your style guide and get rid of ng-controller and ng-app, and just found that I need to share this global state over $rootScope. It doesn't look clear enough so I guess you have some other solution? Do you have some directive in body tag like this:

<body global-variables>

which controllerAs expose funcionality to all views?

from angularjs-style-guide.

batjaa avatar batjaa commented on May 31, 2024

One of my approach of taking care of global variable was creating a service/factory and initialize the data on my root controller/starting point.

app.factory('globalVars', function(){
    var _bar = 100;
    var _foo = 200;

    return{
        bar: _bar,
        foo: _foo,
        x: _x,
        y: _y
    }
})

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

but in this case you have ng-controller="root" somewhere in DOM?

from angularjs-style-guide.

batjaa avatar batjaa commented on May 31, 2024

That can depend on your logic. You can pass some variables when you want to initialize them or you just pre-define all global variables.

And then I can just inject the factory in my controller.

In my case I've used ui-route and had an abstract state which initialized my root controller.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

do you have some sample project or tuts for this? I don't understand how do you pass some variables, I mean where do you pass it?

thanks

from angularjs-style-guide.

batjaa avatar batjaa commented on May 31, 2024

Lemme see how I can help ;)

from angularjs-style-guide.

batjaa avatar batjaa commented on May 31, 2024

http://jsfiddle.net/18apq61L/

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

hey, thank you very much for your fiddle! so I understand it, but, if we want to follow this style guide and write an angular app without ng-controller and ng-app, is it possible and how? that's my confusion

from angularjs-style-guide.

batjaa avatar batjaa commented on May 31, 2024

It's possible. I just wrapped it in the run() method because I wanted to GET some data from the database, as I have mentioned constantly used look up data.

In case you only want to use it as a global variable access way you can create the factory, set the data and then just call inject the factory wherever you want and get your data.

I hope it helps.

On Fri, Dec 5, 2014, 12:54 PM Aleksandar Djindjic [email protected]
wrote:

hey, thank you very much for your fiddle! so Iunderstand it, but, if we
want to follow this style guide and write an angular app without
ng-controller and ng-app, is it possible and how? that's my confusion


Reply to this email directly or view it on GitHub
#20 (comment)
.

from angularjs-style-guide.

feelepxyz avatar feelepxyz commented on May 31, 2024

We currently handle access to the current user/authentication using ui-router.

Any route that needs the current user is nested under a authRequired route.

// Base route
$stateProvider.state('authRequired', {
  abstract: true,
  resolve: {
    currentUser: [
      'CurrentUser',
      function currentUserResolver(CurrentUser) {
        return CurrentUser.getCurrentUser();
      }
    ]
  }
});

// Nested route
$stateProvider.state('authRequired.customers.index', {
  url: '/customers',
  template: template,
  controller: 'CustomersIndexController',
  controllerAs: 'ctrl',
  resolve: {
    customers: [
      'Customers',
      function customersResolver(Customers) {
        return Customers.findAll();
      }
    ]
  }
});

// CurrentUser
var findUser = HttpFactory.create({
  url: API_URL + '/users/:id',
  interceptor: AuthInterceptor,
  cache: true
}, {
  findOne: { method: 'GET' }
});

function getCurrentUser() {
  return ApiKeyStore.get().then(function(apiKey) {
    return findUser.findOne({ params: { id: apiKey.links.user } } );
  }).then(function (data) {
    return data;
  }).catch(function (reason) {
    return $q.reject(reason);
  });
}

This way authentication is handled globally by always requesting a resource that will 401 if you're not signed in. When requested $http caches the response. Calling CurrentUser.getCurrentUser() again will just return the cached version.

Let me know if that makes sense.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

thanks @batjaa and @harrison. It does makes sense, looks very clear! But, if you have some widgets on every page (for example current user status in upper right corner), does it means that you need a root page to be nested under authRequired to get currentUser in this widget?

from angularjs-style-guide.

feelepxyz avatar feelepxyz commented on May 31, 2024

Yep in a way, all pages are nested under authRequired which renders the app frame with the current user.

Here's the complete authRequired route:

$stateProvider.state('authRequired', {
  abstract: true,
  views: {
    '': {
      template: '<auth-required role="ctrl.role"></auth-required>',
      controllerAs: 'ctrl',
      controller: 'AuthRequiredRouteController',
      resolve: {
        role: [
          'CurrentRole',
          function roleResolver(CurrentRole) {
            return CurrentRole.getCurrentRole();
          }
        ]
      }
    },
    'site-header': {
      template: '<site-header current-user="ctrl.currentUser" organisation="ctrl.organisation"></site-header>',
      controllerAs: 'ctrl',
      controller: 'AuthRequiredSiteHeaderController',
      resolve: {
        'organisation': [
          'CurrentOrganisation',
          function organisationResolver(CurrentOrganisation) {
            return CurrentOrganisation.getCurrentOrganisation();
          }
        ]
      }
    }
  },
  resolve: {
    currentUser: [
      '$state', 'CurrentUser',
      function currentUserResolver($state, CurrentUser) {
        return CurrentUser.getCurrentUser()
          .catch(function() {
            $state.go('users.login');
          });
      }
    ]
  }
});

index.html

<body data-main-app ng-cloak>
  <ui-view name="site-header"></ui-view>
  <div>
    <ui-view></ui-view>
  </div>
</body>

auth-required.html

<nav>
  ....
</nav>
<main>
    <ui-view></ui-view>
  </main>
</div>

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

Thank you very much good man! This is very valuable knowledge for me to hear real project experience.
I see that you inject CurrentUser, Role, Org factories (?) in route resolve. It has been my original question where this logic belongs? I guess it doesn't in $rootScope but just want to check is this factories in mainModule (I cant find it in folder structure) or (my current idea at my knowledge level) you have all global factories, services and providers in 'data-main-app' directive logic?

from angularjs-style-guide.

feelepxyz avatar feelepxyz commented on May 31, 2024

For CurrentUser the request is cached by $http so we just call getCurrentUser whenever we need the user anywhere else in the app and get the cached version. To request the right user we use an api key we store in localStorage, which is set on sign in. Otherwise we usually store data inside services for a session, and have getters/setters to work with it.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

Sorry but I cant catch it, is this global variables?

// CurrentUser
var findUser = HttpFactory.create({
  url: API_URL + '/users/:id',
  interceptor: AuthInterceptor,
  cache: true
}, {
  findOne: { method: 'GET' }
});

function getCurrentUser() {
  return ApiKeyStore.get().then(function(apiKey) {
    return findUser.findOne({ params: { id: apiKey.links.user } } );
  }).then(function (data) {
    return data;
  }).catch(function (reason) {
    return $q.reject(reason);
  });
}

or, from where is CurrentUser injected? You haven't got an CurrentUser object literal, class or factory?

app.factory("CurrentUser", [ function() {
...
}]);

sorry if this is stupid question (?) for me it is logical to ask.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

Hey, I think I've got it now :)
so I've found that you guys have your own http-factory and you probably make it in main or some else app module. thanks!

from angularjs-style-guide.

feelepxyz avatar feelepxyz commented on May 31, 2024

ah yes sorry didn't mention, CurrentUser is a factory.

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

thanks again :) 👍

from angularjs-style-guide.

feelepxyz avatar feelepxyz commented on May 31, 2024

@djindjic we just published an example app: https://github.com/gocardless/es6-angularjs

from angularjs-style-guide.

djindjic avatar djindjic commented on May 31, 2024

that's it, I will enjoy research this example!

from angularjs-style-guide.

Related Issues (15)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.