javascript - Angularjs 指令附加 $http 请求

标签 javascript angularjs angularjs-directive

我想创建一个 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/

相关文章:

javascript - Angular typeahead 异步结果 - 在“运算符中接收错误 "TypeError: Cannot use ',以在...中搜索...”

javascript - anchor 标记上的 ng-disabled 有效,但标记仍然可单击

angularjs - 替换表的 Angular 指令

html - 什么元素在中心?

javascript - 从函数中的查询获取结果并计算 Codeigniter 中的 num_rows

javascript - ElectronJS/OSX - 使用我的应用程序打开文件,如何使用 Apple 事件?

javascript - 在 javascript eslint 中允许使用分号

javascript - 如何使用jquery获取变量中元素的文本?

javascript - 为什么使用 $compile 会使工厂执行多次

javascript - ngInfiniteScroll 被调用的次数超出了其需要的次数