I'm stating to learn AngularJS, coming from a lot of different MV* frameworks. I like the framework, however I'm having trouble with passing data between Controllers.
Suppose I have a screen with some input (input.html) and a controller, let's say InputCtrl.
There's a button on this view which takes you to another screen, let's say approve (approve.html) with a controller ApproveCtrl.
This ApproveCtrl needs data from the InputCtrl. This seems like a very common scenario in bigger applications.
In my previous MV* frameworks, this would be handled like (pseudo-code):
var self = this; onClick = function() { var approveCtrl = DI.resolve(ApproveCtrl); approveCtrl.property1 = self.property1; approveCtrl.property1 = self.property2; self.router.show(approveCtrl); }
Now, in AngularJS, I'm handling this like:
var self = this; onClick = function(){ self.$locationService.path('approve'); }
I find it hard to control the state of the created Controller and pass data to it. I've seen and tried following approaches, but all have it's own issues in my opinion:
Am I missing something here? Am I creating too many small Controllers? Am I trying to hold on to habits from other frameworks too much here?
Passing Data Forward to a View Controller To pass data forward to the next view controller, expose properties on the next view controller. In this example, we'll expose a data property of type NSString. In your own project you can use whatever data type you wish, including custom objects.
In terms of structure AngularJS is more Modular than MVC one.
Classic MVC describes 3 simple layers which interact with each other in such way that Controller stitches Model with View (and Model shouldn't rather work with View directly or vice versa).
In Angular you can have multiple, some completely optional, entities which can interact between each other in multiple ways, for example:
That's why there are multiple ways of communicating your data between different entities. You can:
this
and $scope
or
...and a lot more. Due to its diversity Angular allows developer/designer to choose way they are most comfortable with and carry on. I recommend reading AngularJS Developer Guide where you can find blessed solutions to some common problems.
If your intent is to simply share data between two views, a service is probably the way to go. If you are interested in persisting to a data store, you may want to consider some sort of back-end service such as a REST API. Take a look at the $http service for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With