Search code examples
angularjscontrollers

Angularjs Controllers Don't Work


Edit: I found the problems. Thank you everyone for pointing them out to me! :)

I'm a little new to angularjs. Right now, my ng-view and ng-include are working, however my controllers are not. They were working before, but I cannot figure out why this isn't working.

I'm developing on a mac, testing with safari. (Chrome doesn't work when developing locally due to security purposes).

The controllers stopped working when I separated them into different files.

index.html

<html ng-app="socialApp">
<head>
    <script src="assets/jquery/jquery.js"></script>
    <script src="assets/bootstrap/js/bootstrap.min.js"></script>
    <script src="assets/angular/angular.min.js"></script>
    <script src="assets/angular/angular-route.js"></script>
</head>

<body>
    <div ng-include="'partials/header.html'"></div>
    <div ng-view></div>
    <script src="config.js"></script>
</body>

header.html

<div ng-controller="HeaderController">

{{header}}
</div>

headerController.js

var socialApp = angular.module('socialApp', []);
socialApp.controller('HeaderController', function($scope) {
  $scope.header = 'Hello World!';
});

Solution

  • Instead of this:

      when('/friends', {
        templateUrl: 'partials/friends.html',
        controller: 'controllers/siteController.js'
      })
    

    You may need to write this:

      when('/friends', {
        templateUrl: 'partials/friends.html',
        controller: 'FriendsController'
      })
    

    And also you need to link all the js files of your controllers in your html file.

    And and, you should create the socialApp module only once with angular.module(MODULE_NAME, [DEPENDENCY_MODULES, ...]). In the later files when you need to use it, just get a reference through angular.module(MODULE_NAME).