0

I have two questions:

  1. I have a form. After the user pushed the save button, a put-request is fired to the server. The response contains the id of the new object. Now i wanna change the route from test.com/object to test.com/object/1. Since I have all informations, I don't wanna run the controller again (that would load the object again from the server, but this is useless). Short version: How to change the route, without reloading the controller? If this is not possible, which is the best approach?

  2. I have two controller, which are very similar. A good example is a createObject- and a editObject-Controller. I wanna share almost every function, but there are some controller specific methods wich differ. I love services, but in this case I don't see the big advantage, because I don't wanna share just the logic, I wanna share the definition of event-handlers itself. Short version: Which is the way to create inheritance for controllers?

I'm looking forward to answers and good ideas! Thanks a lot!

Cheers

PSL
  • 123,204
  • 21
  • 253
  • 243
user1879408
  • 1,948
  • 3
  • 17
  • 27

2 Answers2

2

The typical (built-in) Angular way to change the route but not the view (or controller) is to only change the search part of your URL via $location.search('someSearchParam', searchParamValue). reloadOnSearch has to be set to false for this to work properly. When the URL changes, event $routeUpdate is broadcast, so your controller can listen for this event to know that something has changed. See also AngularJS Paging with $location.path but no ngView reload

Controller inheritance is probably not a good idea. You could use one controller and ng-show/hide to show the "create" or "edit" version of the page, as indicated by a $scope property, e.g., $scope.editMode:

<div> 
  <span ng-show="editMode">Edit Object</span>
  <span ng-hide="editMode">Create Object</span>
</div>
<div>Name: <input type="text" ng-model="name"></div>
...
<div>
  <input type="submit" ng-show="editMode" ng-click="update()">Update
  <input type="submit" ng-show="editMode" ng-click="create()">Create
</div>

If you do want to try controller inheritance, note that scopes inherit, not controllers. Controller scopes prototypically inherit from their parent scopes. For more on this topic, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
0

Thanks Mark, you helped me a lot!

The route change thing does not really satisfy me, but I think this is the only way for the moment. In my opinion it should be possible to change the route and not just the parameters, without reloading any controllers. Hopefully that will be possible in a future release!

user1879408
  • 1,948
  • 3
  • 17
  • 27