我想创建一个angularjs指令,在ajax调用之后附加新指令。
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){
}
}
});
我想在$ http结果后附加指令。但它之前附加了。 我应用$ scope。$ watch(scope.searchResult)但不起作用。
答案 0 :(得分:1)
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);
}
})
}
或者您可以在ng-if
html
答案 1 :(得分:0)
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);
});
}
}