Search code examples
angularjsbrowserifybundling-and-minificationcommonjs

Relative path not found when requiring a Angular component


Im using Browserify for bundling and Angularjs framework. The scenario is , i have a Angularjs component which has a directive defined as -

var loginDirective = /*@ngInject*/ function(){
  return{
    templateUrl:'views/login/templates/loginComponent.html',
    link:function(scope,ele,attr){
    }
  }
};

This works perfectly when i run the component alone using browserify. Now i have a project "MyAPP" where i use NPM install to get this component in my project's node_modules folder. I then require this componet and include do the DI in the project like this

var angular = require('angular');
require ('baseComponent');

module.exports = angular.module('mainComponent',['baseComponent'])

The DI works fine , but i get a error saying the components 'views/login/templates/loginComponent.html' could not be found cause it starts searching in my projects view folder instead of the its own view folder.

How to resolve this issue ?


Solution

  • I think the common way is to put the template into your JavaScript-Code and load it into the template Cache manually. Like this:

    angular.module('mainComponent').run(function($templateCache) {
        var template = '<h1> LoginComponent </h1>';
        $templateCache.put( 'loginComponent.html' , template );
    });
    

    And your templateUrl in the directive should look like this:

    var loginDirective = /*@ngInject*/ function(){
       return{
          templateUrl: 'loginComponent.html',
          link: function(scope,ele,attr){
          }
       }
    };
    

    You can see this in a lot open source libraries like ui-bootstrap, ui-grid e.g.