Use require() outside Node.js

By : Voles

I'm experimenting to get an Angular.js application working with Node.js.

Currently I have the code below in the file MY-PROJECT/public/js/controllers.js

function LoginController( $scope )
  // fetch waiters
  var Waiter = require( '../models/waiter.js' );
LoginController.$inject = ['$scope'];

As you can see, I'm using require() to access a model file. But it seems like the require()-function is not accessible in this file / folder.

The error I get in the console when I visit the page is:

ReferenceError: require is not defined

The reason for the error is most certainly because I directly include this controllers.js-file in my HTML-file with script-tags (so the require()-function from Node.js is not available).

Now my question is: how can I access a model-file (eg. from MY-PROJECT/models/waiter.js) in the controllers.js-file?

Many thanks in advance!

By : Voles


I was doing it all wrong. Because I'm making a 'realtime-app' (is that the correct name?) and using, it works differently.

In the client-controller, I send a message to the server to request the data. The server fetches the data and send it back to the client.

So in the client I actually don't need to require the model, because I get the data in JSON-format from the server.

This is how I solved it, may be useful to others:

* Login controller
function LoginController( $scope, socket )
    // listen to server when it sends you the cats
    socket.on( 'here-are-all-the-cats', function ( cats )
        $scope.cats = cats;

    // send message to the server, to request the waiters
    socket.emit( 'i-want-all-the-cats' );
WaiterController.$inject = [ '$scope', 'socket' ];

Note: I used 'cats' instead of 'waiters', just to make it more clear to others.

By : Voles

RequireJS looks like it has what you need.

This video can help you solving your question :)
By: admin