0

I am working on a project with a PHP backend and Angular 1.x on the front end. I have a Listings model and I use a common template to create (add) and update (edit) a Listing.

Since eidt and add both use the same front end template I need to be able to detect when a user is creating and when they are editing. It seems there are several ways to do this:

  1. I could pass a paramater in the ng-submit:

    ng-submit="saveListing({{isNewListing}}"
    

Then I could read the value of the paramter in my controller, but I think this is overkill?

  1. When editing a Listing some variables set for the form auto-fill

    $scope.listing.id = x;
    

Therfore I could just check for a value in the above:

$scope.saveListing = function() {
    if(listing.id) {
         // update action
    } else {
         // save action
    }
};

Is the second option a sound and non-hacky approach. I am not an Angular pro so although it seems the logical approach to me I want to ensure that I am not hot woring this.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Alan A
  • 2,557
  • 6
  • 32
  • 54
  • Don't use double curly brackets `{{ }}` with the `ng-submit` directive. See [Why mixing interpolation and expressions is bad practice](https://stackoverflow.com/questions/51592045/why-mixing-interpolation-and-expressions-is-bad-practice). – georgeawg Jan 04 '20 at 03:13

2 Answers2

2

I usually do something similar to the second approach. Since editing means you have to "get" the original record in most cases, the record should exist somewhere in the scope. I use ui-router and have a resolve for the record, which means I can check right at the top of the controller:

$scope.isEdit = record != null;

With a scope variable or similar (e.g. controllerAs vm) you can leverage the fact that you're in "edit mode" and change the UI up a bit. Instead of "+ New" on a button you can have "+ Save".

Hope that helps!

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Chad H
  • 584
  • 3
  • 11
0

We have a large ERP system with angularJs as a front-end framework, and we are using the "check id" approach. When updating/edit an item there would be existing id for that item. I think the second approach is good and I don't see any drawbacks.

Basel Issmail
  • 3,847
  • 7
  • 20
  • 36