Wednesday, February 25, 2015

Maintaining controllers in a separate .js file

For small applications / pages we can have the controller script embedded in the HTML page within the script tags, however if the application / page is large and complex then it is advisable to maintain the controller in separate .js files. Also by doing so we can maintain multiple controllers on a single page.

The following sample demonstrates a simple page, where the HTML View and the controllers are maintained in 2 different files


HTML View
<html ng-app="personApp">
<head>
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
</head>
<body>
<div ng-controller="personController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: <b>{{fullName()}}</b>
</div>
    <script src="angular.min.js"></script>
<script src="personController.js"></script>
</body>

</html>

Controller File (personController.js)
var app = angular.module("personApp", []);
app.controller("personController", function($scope) {
    $scope.firstName = "FName";
    $scope.lastName = "LName";
          $scope.fullName = function() {
                   return $scope.firstName + ", " + $scope.lastName;
          }
    });



Search Flipkart Products:
Flipkart.com

No comments: