【问题标题】:Do I need a directive for a search component?我需要搜索组件的指令吗?
【发布时间】:2014-05-13 13:28:33
【问题描述】:

我是 angularJS 的新手,如果我只使用 JQuery,这个任务会很容易,但我正在努力做正确的事情。

基本上,我想要一个文本输入字段,当用户按下搜索(在输入某些内容后)时,我希望能够通过 Ajax 使用该值进行搜索,然后在列表中显示返回的记录.

我知道要做到这一点,我需要使用指令?

我不是在找人来写这个,但是请指出我正确的方向,或者只是提供一些示例以便我自己构建它。

我的指令(到目前为止)

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

    }
};
});

记录搜索.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>

【问题讨论】:

  • 不,你不应该在所描述的场景中使用指令。你需要一个常规的控制器和 html
  • 如果你重用元素,你可以/应该使用指令。
  • 感谢所有 cmets。我正在制作一个可重复使用的“控件”,每种“类型”都有不同的输入。因此,指令是要走的路吗?
  • 是的。如果您在遵循此路径时遇到了一些问题,如果您可以用您遇到的一些更具体的问题来更新您的问题,将会很有帮助。

标签: javascript angularjs model-view-controller


【解决方案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 查询)。

【讨论】:

    【解决方案2】:

    一种方法:

    1- 对于 ajax 调用,您实际上并不需要指令。您应该在控制器中使用 $http 或 $resource 模块进行 ajax 调用,或者在单独的工厂中进行更好的调用。然后你的输入标签中就会有一个 ng-click 指令,它会调用你的搜索函数并传递你的搜索数据。

    2- 要显示数据,您可以使用或不使用指令。您只需将传入数据分配给适当的范围。例如,$scope.data = factoryService.data;类似的东西。

    【讨论】:

      【解决方案3】:

      您不需要自定义指令,您可以将您的 searchInfo 绑定放入实际的输入元素并使用内置的 ng-click 指令。这个原则的一个很好的例子可以在这里找到http://viralpatel.net/blogs/angularjs-controller-tutorial/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-18
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 2010-10-03
        • 2021-11-13
        • 1970-01-01
        相关资源
        最近更新 更多