tholo tholo - 1 month ago 10
HTML Question

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"
}
];
});

Answer

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"
          }
       ];
   });
Comments