2015-08-25 152 views
0

我有一个搜索表单的指令。这会为您提供一个带有<form>标签的模板,自动发送的消息(如“未找到结果”)和可选的建议消息,如“您可以按名称或ID搜索”。动态资源Angularjs

我的问题是,我想重新利用这个指令,例如,搜索书籍,作者或用户在我的应用程序的不同页面。我为他们提供了资源(使用ngResource),所以我想为我的指令动态地传递这些资源,但我不知道如何。我的代码是在这里:

angular 
    .module('my-app') 
    .directive('searchForm', searchForm) 
    .controller('searchFormController', searchFormController); 

function searchForm() { 
    return { 
     restrict: 'E', 
     scope: { 
      info: '@' 
     }, 
     controller: 'searchFormController', 
     templateUrl: 'templates/directives/search-form.html' 
    }; 
} 

function searchFormController($scope, maybe_dynamic_resource_here) { 
    $scope.results = []; 

    $scope.searchSubmit = function(form){ 
     // do the search here calling to the dynamic resource 
    }; 
} 

我的模板:

<form name="searchform" ng-submit="searchSubmit(searchform)" novalidate> 

<div class="wrapper-form center-block well"> 
    <div class="input-group"> 
     <input type="search" ng-model="search" name="search" class="form-control" required> 
     <span class="input-group-btn"> 
      <button class="btn btn-default" type="submit">Search</button> 
     </span> 
    </div> 
</div> 

<!-- mensajes --> 
<div class="msg-info" ng-show="info && !searchform.$submitted"> 
    <i class="fa fa-question-circle"></i> {{info}} 
</div> 

<div class="msg-info" ng-show="searchform.$submitted && !results.length"> 
    <i class="fa fa-exclamation-triangle"></i> No results found. 
</div> 
<!-- /mensajes --> 

<card-of-results ng-repeat="result in results" /> 

</form> 

而且我用我的指令,如:

<search-form 
    info="You can search by name or id." 
/> 

也许我是一个错误的概念,所有因为我是新用角度,但理想对我来说这就是所谓的指令是这样的:

<search-form 
    info="You can search by name or id." 
    resource="Books" <-- this is how I call the dynamic resource 
/> 

如果有更好的方法来做到这一点,所有帮助它非常感谢。

谢谢!

+0

您应该阅读有关隔离范围和数据绑定。你绑定'info'的同样方法也必须绑定'resource',但使用'='来代替。很可能你可能会想要一个'&'绑定一个函数,这样你就可以触发搜索。 – dirkk

回答

0

我明白想你想才达到。我会尽力为我可能会[应用荷

首先我会给检索算法工厂的解决方案。

.factory('SearchAPI', function ($resource) { 
    return { 
     search: function() { 
      return $resource('search/:path/:id', {}, { 
       books: { 
        method: 'GET', 
        params: { path: 'books' } 
       }, 
       authors: { 
        method: 'GET', 
        params: { path: 'authors' } 
       }, 
       users: { 
        method: 'GET', 
        params: { path: 'users' } 
       } 
      }) 
     } 
    } 
}); 

现在用在我的控制器调用看起来像

类型将是本书,作者,用户

$scope.searchSubmit = function(type){ 
     switch(type){ 
     case 'books' : 
     SearchAPI.search().books(function(data){ 

     }); 
     break; 
     case 'authors' : 
      ...... 
    }; 
} 

以上简单

.factory('SearchAPI', function ($resource) { 
     return $resource('search/:path/:id', {}, { 
       get: { 
        method: 'GET', 
        params: { path: '@path' } 
       }, 
     }); 

}); 

然后哟您的电话将是

$scope.searchSubmit = function(type){ 
     SearchAPI.get({path : type}).then(function(data){ 

     }); 
}