在AngularJS中对不同的控制器使用指令

Use directive with different controllers in AngularJS?

本文关键字:控制器 指令 AngularJS      更新时间:2023-09-26

我已经创建了一个搜索框的指令,我想使用不同的视图。下面是指令-

angular.module('jobSeekerApp')
  .directive('searchBoxDirective', function () {
    return {
      restrict: 'E',
      templateUrl: 'templates/searchbox-template.html',
    };
  });

指令模板-

<span class="searchButton"><i class="fa fa-search fa-2x"></i></span>
<input ng-change="search()" ng-model="searchTerm" ng-keydown="deleteTerm($event)" type="text" id="search-box" style="width: 0px; visibility:hidden;"/>

我想在两个视图上使用这个指令,它们看起来像这样-

视图1 -

<div class="panel panel-default companies" ng-repeat="company in companies.companiesList">
    <div class="panel-heading text-center"><a ng-href="/companies/{{company.id}}" class="hvr-sink"><h3 class="well">{{company.company_name}}</h3></a></div>
    <div class="panel-body text-center flexcontainer">
        <div>Location: {{company.location}}</div>
        <div>Founded In: {{company.founded_year}}</div>
        <div ng-if="company.opening">Opening: Yes</div>
        <div ng-if="!company.opening">Opening: No</div>
        <div>Number Of Openings: {{company.no_openings}}</div>
    </div>
</div>

视图2 -

<div class="panel panel-default jobs" ng-repeat="job in jobs.jobsList">
    <div class="panel-heading text-center"><a href="{{job.career_url}}" target='_blank' class="hvr-sink"><h3 class="well">{{job.job_name}}</h3></a></div>
    <div class="panel-body text-center flexcontainer">
        <div>Company: {{job.company_name}}</div>
    </div>
</div>

正如你所看到的,我在我的视图中使用别名companiesjobs,因此我的指令不能影响它所包含的视图。如果我在我的模板中使用companiesjobs,那么它工作得很好。例如,如果把模板改成-

<span class="searchButton"><i class="fa fa-search fa-2x"></i></span>
<input ng-change="companies.search()" ng-model="companies.searchTerm" ng-keydown="companies.deleteTerm($event)" type="text" id="search-box" style="width: 0px; visibility:hidden;"/>

然后它与companies控制器和jobs控制器相关联的视图一起工作。

我如何使用指令与各自的控制器实例?谢谢你。

为Search创建一个简单的视图

创建它自己的控制器

在服务中查找控制器的记录并将数据放入服务变量

this.searchResult = [];
this.search = function(searchText){
    // code to search
    this.searchResult = Result;    
}

现在,当你想使用这个结果时,在当前控制器的这个服务变量上使用watch,比如:

$scope.$watch(function() { return servicename.searchResult ; }, function(newVal, oldval) { 
   if(newval != oldval){
       $scope.data = servicename.searchResult;
       /* Do the rest of stuff */
   }
}, true);

由于搜索函数是异步的,所以我建议避免使用ng-change来调用它。在搜索图标上使用ng-click

<span class="searchButton" ng-click="$ctrl.searchFn()">
    <i class="fa fa-search fa-2x"></i>
</span>
<input ng-model="$ctrl.searchTerm" type="text" id="search-box">

在指令中,使用隔离范围和bindToController

app.directive('searchBoxDirective', function () {
    return {
      restrict: 'E',
      scope: { 'searchTerm': "=",
               'searchFn': "&"
             },
      controller: function () {},
      controllerAs: '$ctrl',
      bindToController: true,
      templateUrl: 'templates/searchbox-template.html'
    };
});
使用

<search-box-directive search-term="companies.searchTerm"
                      search-fn="companies.search()" >
</search-box-directive>
<search-box-directive search-term="jobs.searchTerm"
                      search-fn="jobs.search()" >
</search-box-directive>

search-term属性创建了从父作用域到指令隔离作用域的双向绑定。search-fn属性从父作用域创建一个表达式绑定来隔离作用域。

使用隔离作用域并显式地将搜索词传递给您的指令。比如:

angular.module('jobSeekerApp')
  .directive('searchBoxDirective', function () {
    return {
      restrict: 'E',
      scope: {
        searchTerm: '=' <-- you can use '@' if you don't need two-way binding
      },
      templateUrl: 'templates/searchbox-template.html',
    };
  });

你没有显示你实际上在哪里使用你的指令,但你会通过一个属性传递范围属性(这是在<div>上使用你的指令):

<div search-box-directive search-term="companies.searchTerm"></div>