Tech tutorials How to Implement a Simple AngularJS MVC Application
By Insight Editor / 30 Jun 2014 , Updated on 16 May 2019 / Topics: Application development
By Insight Editor / 30 Jun 2014 , Updated on 16 May 2019 / Topics: Application development
AngularJS implements Model View Controller (MVC) by allowing the model to notify the controller and views when there’s a change in model state. This will be further explained through the creation of a simple application below.
The view we’ll use for this exercise will most likely look familiar to anyone who has experience with HTML.
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS Hello World</title>
<script type="text/javascript" src="lib/angular.js"></script>
<script type="text/javascript" src="controllers/DefaultController.js"></script>
<script type="text/javascript" src="models/FruitModel.js"></script>
</head>
<body ng-app="helloWorldApp">
<div ng-controller="DefaultController">
<div>
<label>Enter text for button:</label><input type="text" ng-model="inputValue" />
<button type="button" ng-click='getFruitsFromModel()'>{{inputValue}}</button>
<button type="button" ng-click='clearFruits()'>Clear Results</button>
</div>
<div ng-show="fruits.length > 0">
<h3>Fruits:</h3>
<div ng-repeat="fruit in fruits">
<span>{{fruit}}</span><br />
</div>
</div>
</div>
</body>
</html>
This view has a few interesting items that need further explanation.
What introductory application would be complete without a couple of buttons to click? These buttons are defined in our view, and you’ll notice they use the ng-click attribute. This attribute is used to tie the button to a click event, which will be defined in the controller.
var helloWorldApp = angular.module('helloWorldApp', []);
helloWorldApp.controller('DefaultController', function ($scope, FruitModel) {
$scope.getFruitsFromModel = function () {
$scope.fruits = FruitModel.getData();
};
$scope.clearFruits = function () {
$scope.fruits = [];
}
});
There are two items of specific interest in this code:
The model in AngularJS is instantiated through the helloWorldApp.service(‘FruitModel’). The service implementation and interworking is beyond the scope of this article, but the important part in this code is to understand this service functions as the implementation of the model.
helloWorldApp.service('FruitModel', function () {
this.getData = function () {
return ['Apple', 'Banana', 'Orange', 'Grapes', 'Tomato', 'Watermelon'];
};
});
Now that we’ve discussed the code behind the application, we should take a look at the interaction of these components.