2016-09-29 65 views
0

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

$手表也应该有一个处理程序。即当值改变时执行的函数 - '$ scope。$ watch([返回监视值的表达式],[change handler],[objectEquality?]);' –

回答

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-ifhtml

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); 
        }); 
      } 
     } 
+0

当渲染指令并且同时调用链接函数时元素将被追加,而不是将它追加到链接中,并将其追加到控制器中的ajax响应中。为id指定searh指令, – Abdul