I have created a directive for a search form that provides a template with a <form>
tag, automated messages such as "No results found," and an optional suggestion message like "You can search by name or id."
However, I am facing an issue where I need to reuse this directive for searching books, authors, or users on different pages of my application. I have set up resources (using ngResource) for each of them, so I want to dynamically pass these resources to my directive but I am unsure how to do so. Here is my code:
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){
// perform the search here using the dynamic resource
};
}
Here is my template:
<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>
<!-- messages -->
<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>
<!-- /messages -->
<card-of-results ng-repeat="result in results" />
</form>
To use my directive, I write:
<search-form
info="You can search by name or id."
/>
Ideally, I would like to call the directive like this:
<search-form
info="You can search by name or id."
resource="Books" <-- this is how I specify the dynamic resource
/>
If there is a better way to achieve this functionality, any help would be greatly appreciated.
Thank you!