Shamoon
Shamoon

Reputation: 43609

Angular View not updating from a model change

I have 2 modals that use the same controller. One has:

    <div id="addToPlaylist" ng-controller="PlaylistModalCtrl">
                    <select name="playlist" ng-model="playlist" ng-options="playlist.id as playlist.name|rmExt for playlist in playlists">
                    </select>

The other has:

<div id="newPlaylist" ng-controller="PlaylistModalCtrl">
<button ng-click="createPlaylist(playlistName);">Save</button>

In my controller, I have:

angular.module('MyApp')
  .controller('PlaylistModalCtrl', function ($scope) {
    $scope.playlists = [];

    $scope.updatePlaylists = function() {
      getPlaylist.then(function (response) {
        $scope.playlists = response.data.data;
        $scope.$$phase || $scope.$apply();
      });      
    }

    $scope.createPlaylist = function(playlist_name) {
      addPlaylist(playlist_name).then(function(response) {
        $("#newPlaylist").modal('hide');
      });
    }

    $scope.updatePlaylists();
  });

So one would expect that my first view would have an updated "playlists" in the dropdown, but this isn't the case. So how can I get that view to be updated?

Upvotes: 0

Views: 1815

Answers (1)

Nikola Yovchev
Nikola Yovchev

Reputation: 10256

You don't seem to understand how scoping works. Here is a plunkr illustrating that two different controllers have different scopes and stuff.

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

As you can clearly see, expecting two controllers to update the same variable would not work because each of them has the variable in its own isolated scope. What you can do to battle that is to implement a pubsub service that listens to some changes for some properties, use emit and broadcast angular functions, or, the best, rethink why you would need the same controller twice in your app and redesign it.

Upvotes: 1

Related Questions