Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we define a angularjs directive in a requirejs module?

I am not exactly sure how to request and define a directive using a requirejs module.

this is my code for the file containing the directive directives/locationBtn.js

    define(['Zf2NVIApp'], function (Zf2NVIApp) {
    'use strict';

    Zf2NVIApp.directive('locationBtn', function() {
        return {
            template: '<div></div>',
            restrict: 'E',
            link: function postLink(scope, element, attrs) {
                console.log("we are in the location btn module");
                element.text('this is the locationBtn directive');
            }
        };
    });

});

this is the code to my main.js file

require.config({
shim: {
},

paths: {
    angular: 'vendor/angular',
    jquery: 'vendor/jquery.min',
    locationBtn: 'directives/locationBtn'
}
});

require(['Zf2NVIApp', 'locationBtn'], function (app, locationBtn) {
// use app here
angular.bootstrap(document,['Zf2NVIApp']);
});
like image 677
Subtubes Avatar asked Feb 26 '13 04:02

Subtubes


People also ask

What is RequireJS in AngularJS?

RequireJS is a JavaScript library that helps in lazily loading JavaScript dependencies. Modules are just JavaScript files with some RequireJS syntactic sugar in them. RequireJS implements Asynynchronous Modules specified by CommonJS. RequireJS offers simple APIs to create and refer to modules.

How to use Require in AngularJS controller?

^require checks elements above the current one in addition to the current element. So you have to use the two directives together for this to work. Otherwise, just define a controller with app. controller and then use it in both directives.

Which prefix is used with the AngularJS directives?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application.


1 Answers

You're close. Given that your 'Zf2NVIApp.js' file contains

define(['angular'], function(angular){
  return angular.module('Zf2NVIApp', []);
});

than you only need to return the value in your directive AMD module definition and it should work:

define(['Zf2NVIApp'], function (Zf2NVIApp) {
  'use strict';

  Zf2NVIApp.directive('locationBtn', function() {
    return {
      template: '<div></div>',
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
        console.log("we are in the location btn module");
        element.text('this is the locationBtn directive');
      }
    };
  });

  // You need to return something from this factory function
  return Zf2NVIApp;

}); 
like image 163
Stewie Avatar answered Nov 02 '22 02:11

Stewie