Adrian Marinica
Adrian Marinica

Reputation: 2201

AngularJS Missing required controller

I want to create two directives that have the following structure:

<div ng-app="myApp">
    <div ui-foo="test">
        <div ui-bar="test2"></div>
    </div>
</div>

First directive is uiFoo, the second one is uiBar.

To define these directives I have setup the following module definition:

angular.module('ui', []).directive('uiFoo', 
    function() {
      return {
        restrict: 'A',
        link: function($scope, element, attrs) {
            $scope.message = function() {
                alert(1);
            };
        }
      };
    }
  ).directive('uiBar',
    function() {
      return {
        restrict: 'A',
        require: '^uiFoo',
        scope: true,
        link: function($scope, element, attrs, uiBarController) {
          uiBarController.message();
        }
      };
    }
  );

angular.module('myApp', ['ui']);

The problem that I am experiencing is known as error/$compile/ctreq (Controller 'uiFoo', required by directive 'uiBar', can't be found!) and the documentation for it can be found here (https://docs.angularjs.org/error/$compile/ctreq?p0=uiFoo&p1=uiBar). I know, a little lackluster.

It doesn't seem to solve my issue.

I've created a JSFiddle for this which you can find here http://jsfiddle.net/A8Vgk/1187/

Thanks!

Upvotes: 1

Views: 6158

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

Like the error says, you're missing the controller on the uiFoo directive.

When you use the require: ^uiFoo, it tells Angular that you want to have access to the controller in the directive called uiFoo.

You didn't define a controller in that directive, so you get the error.

Just define the controller:

angular.module('ui', []).directive('uiFoo', 
    function() {
      return {
        restrict: 'A',
        link: function($scope, element, attrs) {
            $scope.message = function() {
                alert(1);
            };
        },
          controller: function($scope) {
              this.message = function () {
                  alert("works!");
              }
          }
      };
    }
  )

Working Fiddle.

Upvotes: 4

Related Questions