1

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!

1
  • The $ is on the scope, not on the element. Removing it doesn't fix anything, it's just a naming convention. The link function just injects the parameters in that specific order. Commented Feb 16, 2015 at 12:14

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm, I thought that by filling in the scope, it would act as the controller. Makes sense now. The documentation could use a little polish though. :) Thanks for the help!
@AdrianMar My pleasure. I agree about the documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.