Jaskaran Singh Puri Jaskaran Singh Puri - 2 months ago 11
Javascript Question

Unable to get controller loaded into my angularjs module

I'm trying to split my angularjs controllers into files but failing everytime.

Directory Structure:

--public--
--js/controller/resturant.js
--js/master.js
--index.php


Code for master.js

angular.module("rsw",['rsw.controller']);


Code for resturant.js

angular.module('rsw.controller').controller('resturant', ['$scope', '$http', function($scope, $http){
$scope.data="Test"
}]);


Code for index.php

--
<div ng-app="rsw">
<span ng-controller="resturant">
{{ data }}
</span>
</div>
--


EDIT:
I've included only 'master.js' in my index.php, do I need to import 'resturant.js" too?

Answer

You need to use the correct module definition call. That is, angular.module(name) retrieves a module and angular.module(name, [requires]) creates one.

angular.module('rsw.controller', [])
.controller('resturant', ['$scope', '$http', function($scope, $http){
    $scope.data="Test"
}]);

After creating your module, you need to then make it a dependency of your app:

angular.module("rsw",['rsw.controller']);

Fixed code:

angular.module("rsw", ['rsw.controller']);
angular.module('rsw.controller', [])
  .controller('resturant', ['$scope', '$http',
    function($scope, $http) {
      $scope.data = "Test"
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="rsw">
  <span ng-controller="resturant">
    {{ data }}
  </span>
</div>