bookmarker bookmarker - 2 months ago 24
AngularJS Question

Angularjs directive append $http request

I want to create an angularjs directive that appends new directive after ajax call.

var app = angular.module("app",[]);

// This directive is simple search operation.

app.directive("search", function("$http", function($http){
return {
restrict: "E",
template: '<input type="text" ng-model="searchText"/> <button ng-click="search()">Search</button>',
controller: function($scope){
$scope.search = function(){
$http({url: "..."})
.then(function(response){
$scope.searchResult = response.data;
});
}
},
link: function(scope,element){
var directiveHtml = ('<search-result></search-result>');
var directiveElement = $compile(directiveHtml)(scope);
element.append(directiveElement);
}
}
});

app.directive("searchResult", function(){
return {
restrict: "E",
template: "list of the search result",
link: function(scope,element){

}
}
});


I want to append the directive after $http result. But it appends before.
I applied $scope.$watch(scope.searchResult) but does not work.

Answer
    controller: function($scope){
        $scope.search = function(){
            $http({url: "..."})
                .then(function(response){
                    $scope.searchResult = response.data;
                });
        }
    },
    link: function(scope,element){
        $scope.$watch('searchResult', function(results) {
          if (results) {
               var directiveHtml = ('<search-result></search-result>');
               var directiveElement = $compile(directiveHtml)(scope);
               element.append(directiveElement);
          }
        })
    } 

Or you can use ng-if in html

Comments