0

i was testing a small angular directives code then i got the error by firebug console that Failed to instantiate module myApp

see and tell me what is wrong in the above code

  <div ng-app="myApp">
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
  </div>

var myApp = angular.module('myApp', []);

myApp.directive('log', function() {

  return {
    controller: function( $scope, $attrs ) {
      console.log( $attrs.log + ' (controller)' );
    },
    compile: function compile( tElement, tAttributes ) {
      console.log( tAttributes.log + ' (compile)'  );
      return {
        pre: function preLink( scope, element, attributes ) {
          console.log( attributes.log + ' (pre-link)'  );
        },
        post: function postLink( scope, element, attributes ) {
          console.log( attributes.log + ' (post-link)'  );
        }
      };
    }
  };

});

2 Answers 2

2

Where it says compile: function compile( tElement, tAttributes ) {

I think it should say compile: function( tElement, tAttributes ) {

Same difference at the pre: and post: functions a bit further down.

Edit: Your real issue is that your last line needs to invoke the function like so: })();

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

1 Comment

still getting same error "Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument."
0

Not sure why but your fiddle code doesn't work. Used same code in my fiddle and it works

https://jsfiddle.net/sathvike/e7vkqxs8/

If you use this code in your fiddle it works

<div ng-app='myApp'>
    <div log='some-div'></div>
    <p>Have a look at you console!</p>
 </div>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);
 myApp.directive('log', function() {

 return {
     controller: function($scope, $attrs) {
     console.log($attrs.log + ' (controller)');
  },
  compile: function(tElement, tAttributes) {
    console.log(tAttributes.log + ' (compile)');
    return {
      pre: function preLink(scope, element, attributes) {
        console.log(attributes.log + ' (pre-link)');
      },
      post: function postLink(scope, element, attributes) {
        console.log(attributes.log + ' (post-link)');
      }
    };
  }
  };

 }); 
</script>

2 Comments

what was the difference between your code and mine ?
Not sure why, I also added external reference to angularjs library but it didn't work. Sorry can't explain exactly why.

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.