AngularJS指令与指令之间的通信抛出控制器未找到的错误

AngularJS directive to directive communication throwing an error about controller not found

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

我有两个指令,一个用于搜索,一个用于分页。分页指令需要访问搜索指令来找出我们当前正在搜索的属性。当我加载页面时,它抛出一个错误,说Error: [$compile:ctreq] Controller 'search', required by directive 'pagination', can't be found!。然而,我有一个控制器设置在我的搜索指令。

这是我的搜索指令:
angular.module('webappApp')
  .directive('search', function ($route) {
    return {
      templateUrl: 'views/search.html',
      restrict: 'E',
      scope: {
        searchOptions: '=',
        action: '=',
        currentProperty: '=',
        currentValue: '='
      },
      controller: function($scope) {
        $scope.searchBy = $scope.searchOptions[0].text;
        $scope.searchByProperty = $scope.searchOptions[0].property;
        $scope.setSearchBy = function(event, property, text) {
          event.preventDefault();
          $scope.searchBy = text;
          $scope.searchByProperty = property;
        };
        $scope.search = function() {
          $scope.searching = true;
          $scope.currentProperty = $scope.searchByProperty;
          $scope.currentValue = angular.element('#searchCriteria').val();
          $scope.action($scope.searchByProperty, $scope.currentValue, function() {
            $scope.searching = false;
          });
        };
        $scope.reload = function() {
          $route.reload();
        };
      }
    };
  });

这是我的分页指令:

angular.module('webappApp')
  .directive('pagination', function () {
    return {
      templateUrl: 'views/pagination.html',
      restrict: 'E',
      require: '^search',
      scope: {
        basePath: '@',
        page: '=',
        sort: '='
      },
      link: function(scope, element, attrs, searchCtrl) {
        console.debug(searchCtrl);
        scope.searchByProperty = searchCtrl.searchByProperty;
      }
    };
  });

为了让一个指令通过使用require来使用另一个控制器,它需要与包含指令的控制器共享相同的元素,或者它必须是它的子元素。

你不能用你的方式使用require,那里的元素是兄弟元素。

关于指令的Angular文档,包括require

如果用我描述的方式重新排列DOM没有意义,你应该在两个指令中注入一个服务,其中包含你希望在两者之间共享的数据/方法。

注意:你也可以尝试使用指令作用域的$$nextSibling/$$prevSibling属性,但这只会呈现一个非常脆弱的解决方案

你不能在指令中使用require,然而,因为你唯一需要在指令之间传递的是一个字符串,只是将它们绑定到父控制器中的相同属性(它可以是父指令控制器):

...
<div ng-app='app' ng-controller='MyCtrl as ctrl'> 
   <my-dir-one s1='ctrl.message'></my-dir-one>
   <my-dir-two s2='ctrl.message'></my-dir-two>

和第一指令:

app.directive('myDirOne', function ($route) {
  return {
    templateUrl: 'views/my-dir-one.html',
    restrict: 'E',
    scope: {
      s1: '=',
第二指令

app.directive('myDirTwo', function ($route) {
  return {
    templateUrl: 'views/my-dir-one.html',
    restrict: 'E',
    scope: {
      s2: '=',