That1guyoverthr
That1guyoverthr

Reputation: 1151

How to update view from Angular factory

I might be going about this completely wrong, so I'm open to any suggestions. Thank you!

A jQuery event listener passes an element into my quickComposeFactory when clicked (This is the only part I can't change right now :( ).

Here is plunker demonstration.

$('#results').on('click', '.toggleQuickCompose', function() {
    quickComposeFactory.init($(this).parents('.isotope-item'));
});

My Angular factory evaluates the elem and populates my dynamicContent object that my controller should be able to see in the $scope.

app.factory('quickComposeFactory', function() {

    var dynamicContent = {};

    return {

        getDynamicContent : dynamicContent,

        init: function(elem) {
            } else if (elem.attr('phone')){
                dynamicContent.phone = elem.attr('phone');
                $("#QuickComposePhone").modal("show");
            } else {
                $("#QuickComposeFail").modal("show");
            }
        }
    };
});

Since I'm importing my factory into a controller I thought data binding would work like it always does. Problem is, $scope.dynamicContent is never updated for some reason?

htsApp.controller('quickComposeController', ['$scope', 'quickComposeFactory', function($scope, quickComposeFactory){

    $scope.dynamicContent = quickComposeFactory.getDynamicContent;

}]);

Thus my bootstrap modal does not update. Help?

<div ng-controller="quickComposeController" class="modal hide fade" data-backdrop="false">
    <div class="modal-header">
        <h3 id="myModalLabel">Call or Text</h3>
    </div>
    <div class="modal-body">
    <div>Seller did not include an email.  Please contact:</div>
        <h4>{{dynamicContent.phone}}</h4>
    </div>
    <div class="modal-footer">
        <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
</div>

Upvotes: 0

Views: 123

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

Demo Plunker

Two things that needed to be fixed:

  1. If your service is storing a reference to a model, and that model is bound to scope, then you should use angular.copy to preserve the reference:

    init: function(qcObj) {
      if (qcObj.phone) {
        alert(qcObj.phone);
        angular.copy(qcObj, newQuickCompose)
      }
    }
    
  2. Since you are handling a jQuery click event, you need to call $apply to trigger a digest cycle:

    function getPhoneFromElem() {
      $scope.$apply(function()  {
          $scope.dynamicContent = {
             phone: 1234567
          }
          quickComposeFactory.init($scope.dynamicContent);
    
      });
    }
    

Upvotes: 1

Related Questions