Where Should Model State Be Stored In Angular.js

后端 未结 3 1763
死守一世寂寞
死守一世寂寞 2020-12-12 14:38

I\'m finding Angular\'s use of models confusing. Angular seems to take the approach that a model can be anything you like - I.E. Angular does not include an explicit model c

3条回答
  •  -上瘾入骨i
    2020-12-12 14:51

    First of all, let's not forget that Angular is a web based framework and if you "keep your state" solely in an object, it will not survive user hitting refresh on their browser. Therefore, figuring out how to keep state of Model data in a web based application means figuring out how you are going to persist it so that your code will function in a browser environment.

    Angular makes it really easy for you to persist your state using:

    1. A call to a RESTful $resource
    2. An URL representing an instance of your model

    In your simple example, the storing of user actions such as selectedGallery and selectedPhoto can be represented using URL with something like:

    // List of galleries
    .../gallery
    
    // List of photos in a gallery
    .../gallery/23
    
    // A specific photo
    .../gallery/23/photo/2
    

    The URL is critical because it allow your user to navigate the browser history using back and forward buttons. If you wish to share this state with other part of your application, web application provide wealth of methods for you accomplish that using cookie/localStorage, hidden frame/fields or even storing it in your server.

    Once you defined your strategy on how to persist different state of your application, it should be easier to decide if you wish to access these persisted info using a singleton object as provided by .service or an instance via .factory.

提交回复
热议问题