Angularjs指令附加$ http请求

时间:2016-09-29 08:29:13

标签: 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)但不起作用。

2 个答案:

答案 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);
                    });
            }
        }