Search code examples
arraysangularjsangularjs-serviceangularjs-controller

Cannot get simple push/splicing of array to work - AngularJS


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


Solution

  • 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.