我想创建一个 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) 但不起作用。
最佳答案
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);
}
})
}
或者你可以在html
中使用ng-if
关于javascript - Angularjs 指令附加 $http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39765200/