2014-05-13 27 views
1

我是angularJS的新手,如果我只是使用JQuery,這個任務會非常簡單,但我正在努力做到這一點。我想要一個文本輸入字段,並且當用戶按下搜索(鍵入某些內容後)時,我希望能夠通過Ajax使用該值執行搜索,然後在a中顯示返回的記錄。名單。我是否需要一個搜索組件的指令?

我明白要做到這一點,我需要使用指令?

我不想找人寫這篇文章,但請指出我正確的方向,或者只是提供一些例子,以便我可以自己構建它。

MY指令(SO FAR)

app.directive('recordSearch', function() { 
return { 
    restrict: 'E', 
    scope: { 
     searchInfo: '=info' 
    }, 
    templateUrl: 'partials/record-search.html', 
    link: function(scope, element, attr) { 

    } 
}; 
}); 

RECORD-SEARCH.HTML

<label class="item item-input"> 
<span class="input-label">{{ searchInfo.title }}</span> 
<i class="icon ion-search placeholder-icon"></i> 
<input type="search"> 
</label> 

在我實際的頁面

<record-search info="company"></record-search> 
+1

不,你不應該爲描述的場景使用指令..你需要一個常規的控制器和HTML – Dalorzo

+0

如果你重用元素,你可以/應該使用一個指令。 –

+0

感謝您的所有意見。我正在製作一個可重複使用的「控制」,每種「類型」都有不同的輸入。指令是否因此而走? – Gillardo

回答

1

由於您打算重用該元素,因此指令確實有意義。

根據你所描述的東西,我想它會像這樣組織:

directive('mySearch', function(Item){ 
    return { 
    restrict: 'E', 
    // if you want to show results somewhere outside of the directive, you need 
    // to set a two-way binding variable to pass up the scope chain 
    scope: {}, 
    link: function(scope, elem, attrs) { 
     scope.search = function(query){ 
     Item.search(query).then(function(results){ 
      scope.results = results.data; 
     }); 
     }; 
    }, 
    // template contains search button.. could also contain ng-repeat for 
    // results -- it depends on how/where you want to display the results 
    templateUrl: 'my-template.html' 
    } 
}) 
.factory('Item', function($http){ 
    var item = {}; 

    // this factory manages your item data in general, including searches 
    item.search = function(query){ 
    // perform ajax search w/ $http 
    }; 

    return item; 
}) 

...但你的里程可能會因正是你要完成的任務。一般來說,除了使用可重用組件的指令外,還應該使用服務來處理數據(包括AJAX查詢)。

0

一種方式做到這一點:

1-對於ajax調用,您並不需要指令。您應該在控制器中使用$ http或$ resource模塊進行ajax調用,或者在單獨的工廠中更好地進行ajax調用。然後,您只需在輸入標籤中添加ng-click指令,該指令將調用您的搜索功能並傳遞搜索數據。

2-要顯示數據,您可以使用指令或不使用指令。您只需將傳入數據分配到適當的範圍。例如$ scope.data = factoryService.data;相似的東西。

相關問題