Reputation: 6875
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.
Upvotes: 0
Views: 422
Reputation: 1
controller: function($scope, $http){
$scope.search = function(){
$http({url: "..."})
.then(function(response){
$scope.searchResult = response.data;
var directiveHtml = ('<search-result></search-result>');
var directiveElement = $compile(directiveHtml)($scope);
angular.element(document.getElementById('id')).append(directiveElement);
});
}
}
Upvotes: 0
Reputation: 105517
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
Upvotes: 1