Question

Please have a look at the following Plunker project.

I want to keep a list of items in a service which multiple controllers can access. In this example when you select a surname it will come up in the list. However if you set a second name the list is cleared. I just cabn't figure out the logic in the $scope.$watch

Users should also be able to select the "please choose" option to remove the name from the list. Then you should see a list of all items which have a last name selected. As in the image the list below should read:

  • Matt Diff
  • Tom Canty

http://plnkr.co/edit/pbeLvR?p=preview

I'm still looking at this I just had to abstract it away from my code in case I was doing something wrong there.

enter image description here

Was it helpful?

Solution 2

You should save the names and surnames using a hash. Here there is the edited plunkr:

http://plnkr.co/edit/dChHKr?p=preview

The fact is that you need to trace, for each name, the assigned surname. Otherwise, you are not able to remove it from the list once you assign a new one.

OTHER TIPS

If you watch the service method insted of the ng-model and do all the logic in the service (where it actually belongs), that would be a cleaner way to solve the problem. And faster if you index the items object with the firstName.

http://plnkr.co/edit/NxyDCy?p=preview

I think your code was write, seems you were missing "$scope." before first_name & was causing error.. now I can see the log getting printed & no errors.

http://plnkr.co/edit/9BvPJh?p=preview

-Bhaskara

Here - this will do the trick for you:

In your `$watch code, replace

listService.removeItem(oldItem);

with

if (newSurname === undefined || newSurname === null || newSurname === "") {
    listService.removeItem(oldItem);
}

Thus, when a surname is selected and it is valid, it is added to the list. When it is reset or not selected (when previously selected), it is removed from the list.

I hope this is what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top