简体   繁体   中英

How to pass data from controller to directive from ajax call AngularJS

I need to send data to directive when call is successful... Here is my ajax call from my controller:

$scope.items ={
                avatar: ""
 };
$scope.addComment = function(segment) {
    commentFactory.saveComment($scope.form.comment,segment,0,0)
    .success(function(data){
        $scope.items.avatar = data.avatar;
    })
    .error(function(data){
       console.log(data); 
    });

    // Reset the form once values have been consumed.
    $scope.form.comment = "";
};

And here is 2 directive first use to submit form and ajax req, second use to update content on client side. I need in second directive to load content form ajax... Problem now is directive not wait for ajax to finish call...

.directive("addcomment", function(){
    return {
        restrict: "E",
        template: '<input type="submit" addcomments class="btn btn-default pull-right" value="Send" />'
    };
})

.directive("addcomments", function($compile){
    return {
        link: function (scope, element, attrs) {
            var html = '<div>'+scope.items.avatar+'</div>';

            element.bind("click", function(){
                angular.element(document.getElementById('space-for-new-comment'))
                            .append($compile(html)(scope));
            })  
        }
    };
});

Any solution for this?

I just want to show you another way of writing this: You want to put some comments, ok in html:

<div class="smartdivforcomments">
    <div ng-repeat="comment in newComments">
        {{comment.avatar}}
    </div>
</div>

In controller: $scope.newComments = []; Function for adding comments:

commentFactory.saveComment($scope.form.comment,segment,0,0)
.success(function(data){
    $scope.newComments.push({avatar : data.avatar});
})
.error(function(data){
   console.log(data); 
});

Answer to your comment to previous question: You bind to click event that is not angular, so you need to use scope.apply to correctly update your view.

Use a watch in the addcomments directive and wait for the controller scope variable items.avatar to be defined.

.directive("addcomments", function($compile){
  return {
    link: function (scope, element, attrs) {

      scope.$watch('items.avatar', function(newVal, oldVal) {
        // wait for async to finish
        if(scope.items.avatar === undefined) return;

        // loaded, do work now
        var html = '<div>'+scope.items.avatar+'</div>';

        element.bind("click", function() {
          angular.element(document.getElementById('space-for-new-comment'))
          .append($compile(html)(scope));
        });          
      });
    }
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM