tholo
tholo

Reputation: 541

App Doesn't Load When Controller is in Separate File

This is an addition to my question: AngularJS Doesn't Resolve An Array of Objects

As I've stated in my final edit:

I have resolved this by placing controller in the same file where app is defined - app.js. When placed in separate folder it is not working. I do not know why at this point.

but why is this? I've tried several times and app doesn't load when the controller is in separate file - js/controller.js. And I have checked the path, it is correct.

Here is the app:

This is my HTML:

<body data-ng-app="App">
*
*
*

<div ng-controller="Ctrl">
     <p>{{obj.desc}}</p>
</div>

*
*
*
</body>

app.js

var app = angular.module('App', []);

controller.js

app.controller('Ctrl', function($scope) {
    $scope.obj = [
          {
                intro: "intromessage",
                desc: "desc"
          },
          {
                intro: "intromessage2",
                desc: "desc"
          }
       ];
   });

Upvotes: 1

Views: 48

Answers (2)

Vivek Verma
Vivek Verma

Reputation: 303

you can solve this easily . You have to do small modification in your js files.

app.js

var app = angular.module('App', []);
app.controller('Ctrl',homeController);

controller.js

var homeController = function($scope) {
$scope.obj = [
      {
            intro: "intromessage",
            desc: "desc"
      },
      {
            intro: "intromessage2",
            desc: "desc"
      }
   ];
   }

This will work for you. Make sure that in your layout page you include controller js before app js

Example:

<script src="~\controller.js"></script> <!--first-->
<script src="~\App.js"></script> <!--second-->

Upvotes: 1

dbarthel
dbarthel

Reputation: 130

Assuming controller.js is loaded correctly. You need to define the var app in your new file:

var app = angular.module('App'); //Continue your app module
app.controller('Ctrl', function($scope) {
    $scope.obj = [
          {
                intro: "intromessage",
                desc: "desc"
          },
          {
                intro: "intromessage2",
                desc: "desc"
          }
       ];
   });

Upvotes: 1

Related Questions