Separate Angularjs Controllers Into Separate Files
I am using Ui-Router with my AngularJS application, and am wondering how I split my angular controllers into different files to make them much more clean. For example: var app = an
Solution 1:
You need to load the files containing your controllers in your HTML before you load the file that declares your application.
<scriptsrc="/path/to/angular.js"></script><scriptsrc="/path/to/controller1.js"></script><scriptsrc="/path/to/controller2.js"></script><scriptsrc="/path/to/yourapp.js"></script>
Inside each controller file, you would declare a controller like this:
var Controller = function ($scope) {
}
Controller.$inject = ['$scope'];
Inside your main file after you declare the app variable:
app.controller('Controller', Controller);
Solution 2:
you can write your controller in separate file and just include it in your HTML file after you include your app file
<!DOCTYPE html><html><head><metaname="viewport"content="width=device-width" /><scriptsrc="~/Scripts/angular.js"></script><scriptsrc="~/Scripts/Demo.js"></script><scriptsrc="~/Scripts/DemoController.js"></script><title>Demo</title></head><body><divng-app="demoApp"><divng-controller="demoController"><span>{{dummyData}}</span></div></div></body></html>
code of Demo.js
vardemoApp= angular.module('demoApp',[]);
code of DemoController.js
demoApp.controller('demoController', function($scope) {
$scope.dummyData = "hello from demo app";
});
Post a Comment for "Separate Angularjs Controllers Into Separate Files"