javascriptangularjsng-controller

Component disappears when adding a new controller in AngularJS


New to AngularJS and currently working on an introductory project to get me familiar with the technology.

I've based my application on the angular-seed project that uses ngRoute to show components depending on what link is followed. I have a component, pageHeader, that I'm using to define the links at the top of the page:

angular.
  module('DataStructureVisualizer').
  component('pageHeader', {
    template:
      '<div id="header">' + 
      '<center>' + 
        '<a href="#!/BinaryTree">Binary Tree</a>' + 
        '<a href="#!/Stack">Stack</a>' + 
        '<a href="#!/Queue">Queue</a>' + 
        '<a href="#!/Heap">Heap</a>' + 
        '<a href="#!/LinkedList">Linked List</a>' + 
      '</center>' + 
      '</div>',
    controller: function PageHeaderController() {

    }
  });

This way in index.html I can specify the tag and have AngularJS fill out the DOM with the header HTML.

This works fine, but when I link in another script that defines the following controller:

angular.
  module('DataStructureVisualizer', []).
  controller('DragDropController', function DragDropController($scope) {
    $scope.captureCoordinate = function($event) {
      $scope.x = $event.x;
      $scope.y = $event.y;
    }
  });

The header disappears. What is the reason for this? I'm unsure on how to debug the application, as the Chrome JS console doesn't have any output and the NodeJS server isn't spitting out any errors (not sure why it would, as I'm not doing any server-side stuff, but thought that I should mention).

This is what my app.js looks like:

'use strict';

// Declare app level module which depends on views, and components
angular.module('DataStructureVisualizer', [
  'ngRoute',
  'DataStructureVisualizer.bst',
  'DataStructureVisualizer.heap'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/BinaryTree'});
}]);

Solution

  • Using module('DataStructureVisualizer', []) you're actually telling angular to consider it as a new module that's why it's not working coz you've already defined a module with the same name in your app.js file. You should change it to

    angular.module('DataStructureVisualizer').controller('DragDropController', 
    function DragDropController($scope) {
    $scope.captureCoordinate = function($event) {
      $scope.x = $event.x;
      $scope.y = $event.y;
    }
    });
    

    Hope this helps!