2014-05-13 28 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;相似的东西。

相关问题