Wednesday, July 08, 2015

How to configure Cordova App to use AngularJS

Hi,

In this blog post i am showing how to Add AngularJS library to an existing Cordova App in Visual Studio 2015. The post shows some tips on organizing your JS files into Crodova App project template.

Since i didn't find an example on how to incorporate AngularJS library in Cordova App with out the need to collect various JS files and place them in proper folder structure that works with Cordova App project template. This blog will guide in a step by step how to incorporate AngularJS in Crodova App using VS 2015.

What are we doing ?
Since the AngularJS framework helps developers to follow MVC pattern. We will be creating an out-of-the box Cordova application, then we will add a controller js file and then will set a value in the controller and bind in view page.

Follow below steps to have a running Corodva App with AngularJS installed and configured!

1) Create a Crodova project in VS2015.


2) From Solution explorer window, Click on Manage NuGet Packages.
3) Search for AngularJS and add AngularJS.Core to your project.


4) All AngularJS files will be added under Scripts folder.


5) Select All AngularJS files and move it under scripts folder under www folder.



This is a best practice to include all Cordova App JS files under scripts folder, Since VS 2015 adds JS libraries under Scripts folder as a standard location, we need to move it under scripts folder under www folder.

6) Create a controllers folder  and then add MainCtrl.js file as your controller.
7) Open index.html and add a reference to angular.js and MainCtrl.js.

  <!-- AngularJs -->
    <script src="scripts/angular.min.js"></script>

    <!-- Controllers -->
    <script src="controllers/MainCtrl.js"></script>

8) Add the following code snipped in MainCtrl.js controller , which sets a value for myname in the scope.


(function () {

    angular.module('myApp', [])
    .config([function () {
        // configuration
    }])
    .run([function () {
        // Running
    }])
    .controller('MainCtrl', ['$scope', function ($scope) {
        $scope.myname = "Mostafa Elzoghbi Demo!";

    }])

})();

9) Open up index.html and retrieve (bind) myname value from the controller; set the angularjs app name and the controller name.

<body ng-app="myApp" ng-controller="MainCtrl">
    <p>Hello, your application is ready!</p>
    <p>{{myname}}</p>

10) Run your project! and you will see that myname binding value from the controller.



The full demo can be downloaded from this link:

https://drive.google.com/file/d/0B3qz_TH6n68UTk5RT1A4QmU1S3c/view?usp=sharing
Post a Comment