2016-09-29 101 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