1
votes

I have an angular directive that looks like this:

myApp.directive('foo', function() {
      return {
        template: '<span>{{foo.bar}}</span>',
        restrict: 'E',
        scope: true,
        controller: 'myController'
      };
    });

EDIT I set the directive initially with this controller:

 myApp.controller('myController', function ($scope, MyModel) {
        $scope.foo = MyModel.get();
  });

and it seems to work fine to modify the model from a second controller:

myApp.controller('myOtherController', function($scope, MyModel) {
  setTimeout(function() {
    MyModel.set({
      bar: "biz"
    });
  }, 3000);

});

but not with this controller code:

myApp.controller('myOtherController', function($scope, MyModel) {
   $http.get("/resource").then(function(response) {
    MyModel.set(response.data);
  });
});

I have confirmed that the model updates in both instances, but the directive does not update the view with the $http request.

Here is a Plunker that will give you the general idea.

I have tried all sorts of $timeout/$scope.$apply solutions and they all either do nothing or through a digest in progress error. Any help would be appreciated

1
Where are you setting anything that should be updated? What does your MyModel service look like?Phil
The model is on the plunker. The example with the time out simple changes the model and that change is automatically propagated to the directive.Jeremythuff

1 Answers

0
votes

When you use .then(), the data for your response is in response.data

myApp.controller('myController', function($scope, MyModel) {
  $scope.foo = MyModel.get();

   $http.get("/resource").then(function(response) {
    MyModel.set(response.data);
  });

});

The .success() method of a promise passes response.data as the first argument:

myApp.controller('myController', function($scope, MyModel) {
  $scope.foo = MyModel.get();

   $http.get("/resource").success(function(response) {
    MyModel.set(response.data);
  });

});

Also, you initialize $scope.foo = MyModel.get() when you initialize your controller, so the value of $scope.foo will be the old value after you call MyModel.set(). To fix:

myApp.controller('myController', function($scope, MyModel) {
  $scope.foo = MyModel.get();

   $http.get("/resource").then(function(response) {
    MyModel.set(response.data);
    $scope.foo = MyModel.get();
  });

});

Here is a working Plunk

The only change I had to make was in the data being sent from your run function

.run(function($httpBackend) {
    var res = {
        bar: "It WORKED"
    };

Not quite sure what the purpose of the $timeout calls is in your factory implementation, and your MyModel factory seems a bit complicated (I think there are much easier ways to accomplish what you are after).