Thursday, August 25, 2016

AngularJS And ASP.NET MVC Movie Library Application - $Watch And $Digest Underhood - Part Six

Hope you have had a chance to look at the last tutorial, which talks about the technology stack and creating UI HTML pages with the module and controller and Event Binding with UI elements, as well as routing in Angular JS with partial templates.
Kindly find links here as shown below:

Moving ahead in this article, we’ll try to understand about Watch and Digest, which play a vital role from an AngularJS perspective. In the last article, we have seen the integration of IMDB API, which was in Angular context.
First, we’ll try to use watch on a textbox, as shown in the image, given below:
As the name implies the $scope.watch() function, keeps watch on some variable and looks at their behavior. Whenever you register a watch, you need two functions as the parameters to the $watch() function:
Here is an example,

  1. $scope.$watch(function() {}, 
  2. function() {} 
  3. ); 

Value functions -> which watches the current value of the parameter and returns.
A listener function-> the listener function acts on the value that has changed and takes an adequate action to change the content of another variable or may prompt something, as per the business need.
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value, the watch function returned the last time. In this way, AngularJS can determine, if the value has changed. Here is an example:

  1. $scope.$watch('searchByTitle', function (newValue, oldValue) { } 
  2. $scope.$watch('searchByTitle', function (newValue, oldValue) { } 

This example value function watches the textbox ‘searchByTitle”. If the value of this variable changes, a different value will be returned and AngularJS will call the listener function. Later on the basis of the value, being the watch listener function, performs the written logic.
Let see this implementation practically.
I’ve written the code segment in such a way, so that we can understand an actual fact easily. Kindly find a code segment, as shown below:

  1. routingApp.controller("ApiMovieController", ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) { 
  2.     $scope.SearchMovieByTitle = function () { 
  3.         alert("SearchMovieByTitle called with angular scope"); 
  4. var title = $scope.searchByTitle; 
  5.         alert(title); 
  6.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + title + "&token=5bf94c9e-203f-4a6f-91d0-a63a59a77084&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK").success(function (response) { 
  7.             console.log(response); 
  8.             $scope.movies = response.data.movies; 
  9.         }) 
  10.     } 
  11.     $scope.dateTime = new Date().getMinutes(); 
  12. // alert('in controller');
  13.     document.getElementById('btnSearch').addEventListener('click', callEventListenerfn); 
  14. function callEventListenerfn(e) { 
  15.         alert("SearchMovieByTitleDigest called without angular scope"); 
  16. var title = $scope.searchByTitle; 
  17.         alert(title); 
  18.         $scope.$watch('searchByTitle', function (newValue, oldValue) { 
  19.             $scope.searchByTitle = newValue; 
  20.             console.log("$scope.searchByTitle value changed " + $scope.searchByTitle); 
  21. // alert($scope.searchByTitle);
  22.         }); 
  23.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + $scope.searchByTitle + "&token=2cr22c9e-203f-4a6f-91d0-a63a59a77084&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK") 
  24.           .success(function (response) { 
  25.               alert($scope.searchByTitle); 
  26.               $scope.movies = response.data.movies; 
  27.               $timeout(function () { 
  28.                   $scope.$digest(); 
  29.               }, 100); 
  30.           }) 
  31. // });
  32.     } 
  33. //document.getElementById("btnSearch").addEventListener('click', function () {
  34. //                console.log("Seach Started");
  35. //                alert("Seach Started");
  36. //                $scope.dateTime = new Date().getMinutes();
  37. //                $scope.$digest();
  38. //            });
  39. }]); 

The code above states that the watch function is written in JavaScript eventlistener and it activates as soon as you click the “Search Movie, using EventListner”.
“searchByTitle” is ng-model defined on SeachMovie.html page, which I’ve already shared in the last tutorials. Watch function will evaluate the change made into the input type. "searchByTitle" is shown above in the diagram. This Watch() function will be effective, as soon as you click on Search Movie, using EventListener.
code
Kindly refer to the image, shown below. As soon as I search for any movie, using button Eventlistner and change any value in textBox, it starts reflecting the changes in Console Window.
console
$Scope.Digest()- > As the name implies, Digest means to convert something into absorbable substances. Thus, it works in the same way in AngularJS also. If any event doesn’t appear in Digest cycle, it has to bring into Angular Digest cycle.

  1. $timeout(function () { 
  2. $scope.$digest(); 
  3. }, 100); 

$Scope.Digest()- />
JavaScript eventlistner calls, but sometimes it doesn't update the data bindings. In our case, we are hitting IMDB API, but sometimes, it doesn’t update the $scope.movies collection because the $scope.$digest() is not called after the second button's event listener is executed. To fix it, we can add a $scope.$digest() call to the last line of the button event listener or you can also put the code in $apply function also. Primarily, an objective to put the digest code into $timeout is only because of it to send this code asynchronously.

  1. $timeout(function () { 
  2. $scope.$digest(); 
  3. }, 100); 

Here, is the complete code for searchMovie.html and ApiMovieController, as shown below:
CodeSegment - > searchMovie.html

  1. <!DOCTYPE html> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4.     <h2>Seach Movie Using IMDB API</h2> 
  5.     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
  6.     <style> 
  7.         .selected 
  8.         { 
  9.             background-color: lightyellow; 
  10.             color: red; 
  11.             font-weight: bold; 
  12.         } 
  13.     </style> 
  14. </head> 
  15. <body ng-app="routingApp" class="jumbotron" ng-controller="ApiMovieController"> 
  16.     <div class="container"> 
  17.         <!--<div ng-show="success" class="alert-success">Record has been upddated for movie :  {{updatedMovie.title}}</div> 
  18.          <div ng-show="clear" class="alert-success">Record has been deleted for movie :  {{updatedMovie.title}}</div>--> 
  19.         <div class="row col-md-8"> 
  20.             <table class="table table-striped "> 
  21.                 <tr> 
  22.                     <td> 
  23.                         <input type="text" ng-model="searchByTitle" class="form-control" style="width: 300px;" /> 
  24.                     </td> 
  25.                     {{dateTime}} 
  26.                     <td> 
  27.                         <button type="button" ng-click="SearchMovieByTitle()" class="btn btn-info"> 
  28.                             Search using Angular Scope 
  29.                             <span class="glyphicon glyphicon-search"></span> 
  30.                         </button> 
  31.                         <br /> 
  32.                     </td> 
  33.                 </tr> 
  34.                 <tr> 
  35.                     <td></td> 
  36.                     <td> 
  37.                         <button type="button" id="btnSearch" class="btn btn-info"> 
  38.                             Seacrh Movie Using EventListener 
  39.                             <span class="glyphicon glyphicon-search"></span> 
  40.                         </button> 
  41.                     </td> 
  42.                 </tr> 
  43.                 <tr class="thead-inverse"> 
  44.                     <td style="background-color: Highlight">Title</td> 
  45.                     <td style="background-color: Highlight">Year of Release</td> 
  46.                     <td style="background-color: Highlight">Rating</td> 
  47.                     <td style="background-color: Highlight">Plot</td> 
  48.                     <td style="background-color: Highlight">Actions</td> 
  49.                 </tr> 
  50.                 <tbody> 
  51.                     <tr ng-repeat="movie in movies" ng-class="{'selected':$index == selectedRow}"> 
  52.                         <td>{{movie.title}} 
  53.                         </td> 
  54.                         <td>{{movie.year}} 
  55.                         </td> 
  56.                         <td>{{movie.rating}} 
  57.                         </td> 
  58.                         <td>{{movie.plot }} 
  59.                         </td> 
  60.                         <td></td> 
  61.                     </tr> 
  62.                 </tbody> 
  63.             </table> 
  64.         </div> 
  65.     </div> 
  66. </body> 
  67. </html> 

Code segment for ApiMovieController is given blow:

  1. routingApp.controller("ApiMovieController", ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) { 
  2.     $scope.SearchMovieByTitle = function () { 
  3.         alert("SearchMovieByTitle called with angular scope"); 
  4. var title = $scope.searchByTitle; 
  5.         alert(title); 
  6.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + title + "&token=2gr44c9e-203f-4a6f-91d0-o6121 &format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK").success(function (response) { 
  7.             console.log(response); 
  8.             $scope.movies = response.data.movies; 
  9.         }) 
  10.     } 
  11.     $scope.dateTime = new Date().getMinutes(); 
  12.      alert('in controller'); 
  13.     document.getElementById('btnSearch').addEventListener('click', callEventListenerfn); 
  14. function callEventListenerfn(e) { 
  15.         alert("SearchMovieByTitleDigest called without angular scope"); 
  16. var title = $scope.searchByTitle; 
  17.         alert(title); 
  18.         $scope.$watch('searchByTitle', function (newValue, oldValue) { 
  19.             $scope.searchByTitle = newValue; 
  20.             console.log("$scope.searchByTitle value changed " + $scope.searchByTitle); 
  21. // alert($scope.searchByTitle);
  22.         }); 
  23.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + $scope.searchByTitle + "&token=2gr44c9e-203f-4a6f-91d0-o6121&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK") 
  24.           .success(function (response) { 
  25.               alert($scope.searchByTitle); 
  26.               $scope.movies = response.data.movies; 
  27.               $timeout(function () { 
  28.                     $scope.$digest(); 
  29.               }, 100); 
  30.           }) 
  31. // });
  32.     } 
  33. }]);  

Hope, it’ll help you some day. Enjoy coding.

You can download source code from here:

Download source code form here

Tuesday, August 16, 2016

 $digest already in progress when calling $scope.$apply() in AngularJS

I was getting this error during i made call to a third-party library to access data on their servers, so I can't take advantage of $http, nor do I want to since I would have to rewrite their library to use $http.

$http.jsonp(http://api.myapifilms.com/imdb/idIMDB?title=” “).success(function (response) {
             alert($scope.searchByTitle);           
             $scope.movies = response.data.movies;

  $scope.$digest();

// If i write above $digest method directly i thrown me an error though if i put it into little diff form than it works fine.
$timeout(function () {
                   $scope.$digest();
             }, 100);

 

Reason behind this is ,$timeout function takes this execution as async request.

Thanks

Monday, August 1, 2016

 

AngularJS And ASP.NET MVC Movie Library Application - Integration Of IMDB Movie API - Part Fiv

DotnetPiper_Angular

Moving ahead, in this article, we’ll focus on the integration of live movie API within an existing application.
Kindly open the given URL and register yourself. After registering, you will get a token which we’ll be using in this article to retrieve the information/data from API.
http://api.myapifilms.com/imdb
Once you register yourself, you should receive an email like the given image, with some token value.
value
Open the website with the link, shared above, and fill in the details, as shown below in the following images.
emails
emails
As soon as you click on the submit button, you should receive a response in JSON format, as given below:
response
You may also get XML response for just making amendments either in request or in format dropdown, as shown below:
request
So far so good. We are now able to use this API URL within our application.
Open you solution and find routing.js file to add a new Controller into this, as give below:
solution

  1. routingApp.controller("ApiMovieController", ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) { 
  2.     $scope.SearchMovieByTitle = function () { 
  3. var title = $scope.searchByTitle; 
  4.         alert(title); 
  5.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + title + "&token=5bf98789787hghjg4&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK").success(function (response) { 
  6.             console.log(response); 
  7.             $scope.movies = response.data.movies; 
  8.         }) 
  9.     }]); 

Kindly, put your token value in the above http request, in order to get the correct result.
Note: If you have noticed, in the above code segment, you have injected a dependency $http and $timeout. For now, only concentrate on the $http and forget about $timeout.
code
Complete code for routing.js main JavaScript file is shown below:
Code Routing.js file

  1. /// <reference path="../Scripts/angular.js" />
  2. /// <reference path="../Scripts/fusioncharts.js" />
  3. /// <reference path="../Scripts/fusioncharts.charts.js" />
  4. /// <reference path="DataService.js" />
  5. /// <reference path="../Scripts/angular-route.js" />
  6. var routingApp = angular.module('routingApp', ['ngRoute']); 
  7. routingApp.directive("login", function () { 
  8. var directive = {}; 
  9. //restrict = E, signifies that directive is Element directive
  10.     directive.restrict = 'E'; 
  11. //template replaces the complete element with its text.
  12.     directive.templateUrl = "/Application/Login.html";//"My first directive";
  13. return directive; 
  14. }); 
  15. routingApp.config(['$routeProvider', function ($routeProvider) { 
  16. //alert("Route Initiated");
  17.     $routeProvider. 
  18. // when('/Home', { templateUrl: '/Application/login.html', controller: 'DotnetPiperController' }).
  19.         when('/Movie', { templateUrl: '/Application/Movie.html', controller: 'MovieController' }). 
  20.         when('/SearchMovie', { templateUrl: '/Application/SearchMovie.html', controller: 'ApiMovieController' }). 
  21.          when('/Tolly', { templateUrl: '/Application/Tollywood.html', controller: 'tollyController' }). 
  22.         otherwise({ redirectTo: '' }); 
  23. }]); 
  24. routingApp.controller("tollyController", function ($scope) { 
  25.     $scope.tollyMessage = "Welcome to TollyWood to watch Action,Thriller and Suspence movies"; 
  26. }); 
  27. routingApp.controller("MovieController", ['$scope', function ($scope) { 
  28.     $scope.edit = false; 
  29.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
  30.     $scope.error = false; 
  31.     $scope.clear = false; 
  32.     $scope.success = false; 
  33. // alert("Servcie Called");
  34. var movies = [ 
  35.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
  36.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
  37.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
  38.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
  39.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
  40.     ]; 
  41.     $scope.movies = movies; 
  42.     $scope.AddMovie = function (movie) { 
  43. if ($scope.edit == true) { 
  44. var index = $scope.movies.indexOf(movie); 
  45. // alert("edit Called");
  46.             $scope.movies[index] = movie; 
  47. //alert(movie.rating);
  48.             $scope.updatedMovie = movie; 
  49.             $scope.success = true; 
  50.             $scope.movie = {}; 
  51.         } 
  52. else { 
  53. var newMovie = { 
  54.                 title: $scope.movie.title, 
  55.                 year: $scope.movie.year, 
  56.                 rating: $scope.movie.rating, 
  57.                 plot: $scope.movie.plot 
  58.             }; 
  59.             movies.push(newMovie); 
  60. // alert("Add Called");
  61.         } 
  62.     } 
  63.     $scope.DeleteMovie = function (movie, index) { 
  64.         movies.splice(index, 1); 
  65. // $scope.movie = movie;
  66.         $scope.updatedMovie = movie; 
  67.         $scope.success = false; 
  68.         $scope.clear = true; 
  69.         $scope.movie = {}; 
  70.         console.log(index); 
  71.     } 
  72.     $scope.EditMovie = function (movie, index) { 
  73.         $scope.selectedRow = null;  // initialize our variable to null
  74.         $scope.selectedRow = index; 
  75.         $scope.movie = movie; 
  76.         $scope.edit = true; 
  77.     } 
  78. }]); 
  79. routingApp.controller("ApiMovieController", ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) { 
  80.     $scope.SearchMovieByTitle = function () { 
  81. var title = $scope.searchByTitle; 
  82.         alert(title); 
  83.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + title + "&token=5bf94c9e-203f-4a6f-91d0-a63a59a77084&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK").success(function (response) { 
  84.             console.log(response); 
  85.             $scope.movies = response.data.movies; 
  86.         }) 
  87.     } 
  88.     $scope.dateTime = new Date().getMinutes(); 
  89. // alert($scope.dateTime);
  90.     document.getElementById("btnSearch").addEventListener('click', function SearchMovieByTitleDigest() { 
  91. var title = $scope.searchByTitle; 
  92.         $scope.$watch("searchByTitle", function (newValue, oldValue) { 
  93.             $scope.searchByTitle = newValue; 
  94.             console.log("$scope.searchByTitle Called " + $scope.searchByTitle); 
  95.             alert($scope.searchByTitle); 
  96.         }); 
  97. //console.log(title);
  98. //alert(title);
  99.         $http.jsonp("http://api.myapifilms.com/imdb/idIMDB?title=" + $scope.searchByTitle + "&token=5bc9e-203f-4a6f-91d0-a63a59de4222&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=5&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0&callback=JSON_CALLBACK") 
  100.             .success(function (response) { 
  101.                 $scope.movies = response.data.movies; 
  102.                 $timeout(function () { 
  103.                     $scope.$digest(); 
  104.                 }, 100); 
  105.             }) 
  106.     }); 
  107. //document.getElementById("btnSearch").addEventListener('click', function () {
  108. //                console.log("Seach Started");
  109. //                alert("Seach Started");
  110. //                $scope.dateTime = new Date().getMinutes();
  111. //                $scope.$digest();
  112. //            });
  113. }]); 

We are almost done with our Controller code part. It's now turn to create the UI to meet our purpose.
Kindly open your solution and add searchMovie.html file, as shown below in the screenshot:
searchMovie
Please copy and paste the following code in searchMovie.html partial template.
Code for searchMovie.html file,

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <h2>Seach Movie Using IMDB API</h2>
  5. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  6. <style>
  7.         .selected 
  8.         { 
  9.             background-color: lightyellow; 
  10.             color: red; 
  11.             font-weight: bold; 
  12.         } 
  13. </style>
  14. </head>
  15. <body ng-app="routingApp" class="jumbotron">
  16. <div ng-controller="ApiMovieController" class="container">
  17.         <!--<div ng-show="success" class="alert-success">Record has been upddated for movie :  {{updatedMovie.title}}</div>
  18. <div ng-show="clear" class="alert-success">Record has been deleted for movie :  {{updatedMovie.title}}</div>-->
  19. <div class="row col-md-8">
  20. <table class="table table-striped ">
  21. <tr>
  22. <td>
  23. <input type="text" ng-model="searchByTitle" class="form-control" style="width: 300px;" />
  24. </td>
  25.                     {{dateTime}} 
  26. <td>
  27. <button type="button" ng-click="SearchMovieByTitle()" class="btn btn-info">Search using Angular Scope 
  28. <span class="glyphicon glyphicon-search"></span>
  29. </button>
  30. <br />
  31. </td>
  32. </tr>
  33. <tr>
  34. <td></td>
  35. <td>
  36. <button type="button" id="btnSearch" class="btn btn-info">Seacrh Movie Using EventListener 
  37. <span class="glyphicon glyphicon-search"></span>
  38. </button>
  39. </td>
  40. </tr>
  41. <tr class="thead-inverse">
  42. <td style="background-color: Highlight">Title</td>
  43. <td style="background-color: Highlight">Year of Release</td>
  44. <td style="background-color: Highlight">Rating</td>
  45. <td style="background-color: Highlight">Plot</td>
  46. <td style="background-color: Highlight">Actions</td>
  47. </tr>
  48. <tbody>
  49. <tr ng-repeat="movie in movies" ng-class="{'selected':$index == selectedRow}">
  50. <td>{{movie.title}} 
  51. </td>
  52. <td>{{movie.year}} 
  53. </td>
  54. <td>{{movie.rating}} 
  55. </td>
  56. <td>{{movie.plot }} 
  57. </td>
  58. <td></td>
  59. </tr>
  60. </tbody>
  61. </table>
  62. </div>
  63. </div>
  64. </body>
  65. </html>

Once you paste the above code segment, run an application and click on Search Movie Globally.
Note: Ensure that you had implemented the routing, as shown in the below URL,

The output will be, as depicted below:
output
Mapping of the above textbox search, using Angular Scope. Whatever value we put into the textbox, ApiMovieController reads that value using scope and passes into http request as Title, as depicted in the screenshot below:
code
Now, search for the movie as I’ve done for The Revenant and Sultan, both.
revenent
sultan
Kindly refer tothe given screen for full fledged movie search operation.
output
Hope it’ll help you some day. Enjoy Coding.

Wednesday, July 27, 2016

AngularJS And ASP.NET MVC Movie Library Application - Part Four AngularJS Routing with partial templates

DotnetPiper_Angular

Hope you got a chance to look into my last tutorials about technology stack, creating UI HTML page with Modules and Controllers, and Event Binding with UI elements. Kindly, find the links here:

Moving ahead, in this article, we’ll focus on integration of movie.html page with MVC layout page. Also, we’ll implement Angular routing in that.
Let’s get our hands busy with AngularJS & ASP.NET MVC Movie Library Application - Part Four.
So far, we’ve designed the following screen shot:
portal
For this purpose, I’ve created a few more pages so that we can implement routing easily. Kindly have a look at the image below, for reference.
reference
So, please create other pages as well. Probably after Part 6 of Movie Library Application, I’ll share my application with you for downloading.
Open the Solution Explorer and look for _Layout.cshtml page there. You can give reference of main.js (in our case it is routing.js) file as a reference there also, so that it would be applicable for all .cshtml pages.This is because _Layout page loads first in MVC life cycle.
Routing.js file contains all controllers' code used in all html pages e.g. Movie.html, searchMovie.html and tollywood.html.
It works in such a manner that as soon as the _layout.cshtml page loads, it also loads Module along with all respective controllers defined under this JavaScript file.
Kindly, find the code below for how to bind routing.js file.
code
If you have noticed in the above screenshot, I’ve set the menu using bootstrap which looks like the following screen, now:
screen
Understand ng_view: Another important factor is the usage of ng-view directive. In our angular app, we need to define ng-app directive once. Ng-view becomes the placeholder for views. Each view referred by the route is loaded in this section of the document which we have defined on _layout.cshtml. You can also define ng-view in main html file .There are a few ways to define it, as shown below. I’ve chosen <ng-view></ng-view> tag.
For my purpose, kindly refer to the above screen shot for reference and look at bottom of image.

  1. <div ng-view></div>
  2. <ng-view></ng-view>
  3. <div class="ng-view"></div>

Kindly, find the code below for_layout.cshtml, so that you may fit into your code segment also.
Code snippet _layout.cshtml

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>@ViewBag.Title - My ASP.NET MVC Application</title>
  6. <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
  7. <meta name="viewport" content="width=device-width" />
  8.     @Styles.Render("~/Content/css") 
  9.     @Scripts.Render("~/bundles/modernizr") 
  10. <script src="~/Scripts/angular.min.js"></script>
  11. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
  12.     @*    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>*@ 
  13. <script src="~/Application/App.js"></script>
  14. <script src="~/Application/Routing.js"></script>
  15. </head>
  16. <body>
  17. <header>
  18. <div class="content-wrapper">
  19. <div class="float-right">
  20. <section id="login">
  21. </section>
  22. <nav>
  23. </nav>
  24. </div>
  25. </div>
  26. </header>
  27. <div id="body" ng-app="routingApp" class="float-center">
  28. <nav class="navbar navbar-inverse navbar-fixed-top">
  29. <div class="container-fluid">
  30. <div class="navbar-header">
  31. <a class="navbar-brand" href="www.dotnetpiper.com">DotnetPiper.Com</a>
  32. </div>
  33. <ul class="nav navbar-nav">
  34. <li class="active"><a href="#/Home"><b>Home</b></a></li>
  35. <li><a href="#/Movie"><b>Bollywood</b></a></li>
  36. <li><a href="#/SearchMovie"><b>Seacrh Movie Globally</b></a></li>
  37. <li><a href="#/Tolly"><b>Tollywood</b></a></li>
  38. </ul>
  39. <ul class="nav navbar-nav navbar-right">
  40. <li><a href="#"><span class="glyphicon glyphicon-user"></span>Sign Up</a></li>
  41. <li><a href="#"><span class="glyphicon glyphicon-log-in"></span>Login</a></li>
  42. </ul>
  43. </div>
  44. </nav>
  45. <ng-view></ng-view>
  46.         @RenderSection("featured", required: false) 
  47.         @RenderBody() 
  48. </div>
  49.     @* <footer>
  50. <div class="content-wrapper">
  51. <div class="float-left">
  52. <p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
  53. </div>
  54. </div>
  55. </footer>*@ 
  56.     @Scripts.Render("~/bundles/jquery") 
  57.     @RenderSection("scripts", required: false) 
  58. </body>
  59. </html>

Add Routing in AngularJS
We’ve included a JavaScript file, routing.js, which holds the application logic. Given below is the content of routing.js. Kindly ensure that you have given the reference for route.js, as shown below:

  1. /// <reference path="../Scripts/angular-route.js" />
  2. var routingApp = angular.module('routingApp', ['ngRoute']); 
  3. routingApp.config(['$routeProvider', function ($routeProvider) { 
  4. //alert("Route Initiated");
  5.     $routeProvider. 
  6.         when('/Home', { templateUrl: '/Application/login.html', controller: '/Application/testController' }). 
  7.         when('/Movie', { templateUrl: '/Application/Movie.html', controller: 'MovieController' }). 
  8.         when('/SearchMovie', { templateUrl: '/Application/SearchMovie.html', controller: 'ApiMovieController' }). 
  9.          when('/Tolly', { templateUrl: '/Application/Tollywood.html', controller: 'tollyController' }). 
  10.         otherwise({ redirectTo: '/' }); 
  11. }]); 

First, use .config() method to define $routeProvider configuration. The routeProvider identifies the route, e.g., whenever there will be a string “/Movie” in route URL, it should load template "/Application/Movie.html" from partial templates. (I’m calling these .html pages as partial pages).
After implementing the Routing, it should work in a way, as depicted below. Kindly notice the URLchanging on each click.
output
This is the complete code for routing.js which is main app file.

  1. /// <reference path="../Scripts/angular.js" />
  2. /// <reference path="../Scripts/fusioncharts.js" />
  3. /// <reference path="../Scripts/fusioncharts.charts.js" />
  4. /// <reference path="../Scripts/angular-route.js" />
  5. var routingApp = angular.module('routingApp', ['ngRoute']); 
  6. routingApp.config(['$routeProvider', function ($routeProvider) { 
  7. //alert("Route Initiated");
  8.     $routeProvider. 
  9.         when('/Home', { templateUrl: '/Application/login.html', controller: '/Application/testController' }). 
  10.         when('/Movie', { templateUrl: '/Application/Movie.html', controller: 'MovieController' }). 
  11.         when('/SearchMovie', { templateUrl: '/Application/SearchMovie.html', controller: 'ApiMovieController' }). 
  12.          when('/Tolly', { templateUrl: '/Application/Tollywood.html', controller: 'tollyController' }). 
  13.         otherwise({ redirectTo: '/' }); 
  14. }]); 
  15. routingApp.controller("tollyController", function ($scope) { 
  16.     $scope.tollyMessage = "Welcome to TollyWood to watch Action,Thriller and Suspence movies"; 
  17. }); 
  18. routingApp.controller("MovieController", ['$scope', function ($scope) { 
  19.     $scope.edit = false; 
  20.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
  21.     $scope.error = false; 
  22.     $scope.clear = false; 
  23.     $scope.success = false; 
  24. // alert("Servcie Called");
  25. var movies = [ 
  26.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
  27.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
  28.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
  29.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
  30.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
  31.     ]; 
  32.     $scope.movies = movies; 
  33.     $scope.AddMovie = function (movie) { 
  34. if ($scope.edit == true) { 
  35. var index = $scope.movies.indexOf(movie); 
  36. // alert("edit Called");
  37.             $scope.movies[index] = movie; 
  38. //alert(movie.rating);
  39.             $scope.updatedMovie = movie; 
  40.             $scope.success = true; 
  41.             $scope.movie = {}; 
  42.         } 
  43. else { 
  44. var newMovie = { 
  45.                 title: $scope.movie.title, 
  46.                 year: $scope.movie.year, 
  47.                 rating: $scope.movie.rating, 
  48.                 plot: $scope.movie.plot 
  49.             }; 
  50.             movies.push(newMovie); 
  51. // alert("Add Called");
  52.         } 
  53.     } 
  54.     $scope.DeleteMovie = function (movie, index) { 
  55.         movies.splice(index, 1); 
  56. // $scope.movie = movie;
  57.         $scope.updatedMovie = movie; 
  58.         $scope.success = false; 
  59.         $scope.clear = true; 
  60.         $scope.movie = {}; 
  61.         console.log(index); 
  62.     } 
  63.     $scope.EditMovie = function (movie, index) { 
  64.         $scope.selectedRow = null;  // initialize our variable to null
  65.         $scope.selectedRow = index; 
  66.         $scope.movie = movie; 
  67.         $scope.edit = true; 
  68.     } 
  69. }]); 

Hope it’ll help you some day. Enjoy Coding.

Learn WebAPi and MVC Here

Wednesday, July 20, 2016

AngularJS And ASP.NET MVC Movie Library Application - Part Three- EventBinding with UI Elements

I hope you have had a chance to look into my last tutorial. Here, I will talk about the Event binding with UI elements of Movie.html page within module and controller.

And this will the outcome after binding all control with controller’s function as depicted below:


Kindly find links here as shown below:

Moving ahead in this article, we’ll focus on how to bind UI controls events and link with the defined controller.
$scope plays a vital role whenever you bind the controller value with the specific view. Here, we are going to learn it. After using this, I believe that it would be a kind of ice-breaker and will ease all the further learnings. Let's get our hands dirty with AngularJS & ASP.NET MVC Movie Library Application Tutorials part three.
So far, we’ve designed the screen shot, given below:
screen shot
Hope, you will have also reached up to this level. Moving ahead, let's bind the fancy bootstrap glyphicon icon into an action.
Add the ng-click event, one by one, on each respective control.There are thee HTML button controls that exist. 
First – Add button with + symol
Second – Edit button with pencil symbol
Third - Cross with * Symbol.
Kindly paste the code segment, given below, into the movie.html page.
Code segment Movie.html

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <h2>Movie Rating Portal</h2>
  5. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  6. <style>
  7.         .selected 
  8.         { 
  9.             background-color: lightyellow; 
  10.             color: red; 
  11.             font-weight: bold; 
  12.         } 
  13. </style>
  14. </head>
  15. <body ng-app="routingApp" class="jumbotron">
  16. <div ng-controller="MovieController" class="container">
  17. <div ng-show="success" class="alert-success">Record has been upddated for movie :  {{updatedMovie.title}}</div>
  18. <div ng-show="clear" class="alert-success">Record has been deleted for movie :  {{updatedMovie.title}}</div>
  19. <div class="row col-md-8">
  20. <table class="table table-striped ">
  21. <thead class="thead-inverse">
  22. <th style="background-color: Highlight">Title</th>
  23. <th style="background-color: Highlight">Year of Release</th>
  24. <th style="background-color: Highlight">Rating</th>
  25. <th style="background-color: Highlight">Plot</th>
  26. <th style="background-color: Highlight">Actions</th>
  27. </thead>
  28. <tr>
  29. <!-- <td>EmployeeID:</td>-->
  30. <td>
  31. <input type="text" ng-model="movie.title" class="form-control" />
  32. </td>
  33. <td>
  34. <input type="text" ng-model="movie.year" class="form-control" />
  35. </td>
  36. <td>
  37. <input type="text" ng-model="movie.rating" class="form-control" />
  38. </td>
  39. <td>
  40. <input type="text" ng-model="movie.plot" class="form-control" />
  41. </td>
  42. <td>
  43. <button type="button" ng-click="AddMovie(movie)" class="btn btn-primary">
  44. <span class="glyphicon glyphicon-plus"></span>
  45. </button>
  46. </td>
  47. </tr>
  48. <tbody>
  49. <tr ng-repeat="movie in movies" ng-class="{'selected':$index == selectedRow}">
  50. <td>{{movie.title}} 
  51. </td>
  52. <td>{{movie.year}} 
  53. </td>
  54. <td>{{movie.rating}} 
  55. </td>
  56. <td>{{movie.plot }} 
  57. </td>
  58. <td>
  59. <button type="button" ng-click="EditMovie(movie,$index)" class="btn btn-warning">
  60. <span class="glyphicon glyphicon-pencil"></span>
  61. </button>
  62. <button type="button" ng-click="DeleteMovie(movie,$index)" class="btn btn-danger">
  63. <span class="glyphicon glyphicon-remove"></span>
  64. </button>
  65. </td>
  66. </tr>
  67. </tbody>
  68. </table>
  69. </div>
  70. </div>
  71. </body>
  72. </html>

 

code
Now, we are almost done with the UI part and have created the required ng-click events on all the buttons existing on the page.
Now,  it'stime to design the controller and write the code so that  every button should work very effectively. Thus, please copy and paste the code, given below and replace it within routing.js file.

  1. /// <reference path="../Scripts/angular.js" />
  2. var routingApp = angular.module('routingApp', []); 
  3. routingApp.controller("MovieController", ['$scope', function ($scope) { 
  4.     $scope.edit = false; 
  5.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
  6.     $scope.error = false; 
  7.     $scope.clear = false; 
  8.     $scope.success = false; 
  9. // alert("Servcie Called");
  10. var movies = [ 
  11.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
  12.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
  13.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
  14.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
  15.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
  16.     ]; 
  17.     $scope.movies = movies; 
  18.     $scope.AddMovie = function (movie) { 
  19. if ($scope.edit == true) { 
  20. var index = $scope.movies.indexOf(movie); 
  21. // alert("edit Called");
  22.             $scope.movies[index] = movie; 
  23. //alert(movie.rating);
  24.             $scope.updatedMovie = movie; 
  25.             $scope.success = true; 
  26.             $scope.movie = {}; 
  27.         } 
  28. else { 
  29. var newMovie = { 
  30.                 title: $scope.movie.title, 
  31.                 year: $scope.movie.year, 
  32.                 rating: $scope.movie.rating, 
  33.                 plot: $scope.movie.plot 
  34.             }; 
  35.             movies.push(newMovie); 
  36. // alert("Add Called");
  37.         } 
  38.     } 
  39.     $scope.DeleteMovie = function (movie,index) { 
  40.         movies.splice(index, 1); 
  41. // $scope.movie = movie;
  42.         $scope.updatedMovie = movie; 
  43.         $scope.success = false; 
  44.         $scope.clear = true; 
  45.         $scope.movie = {}; 
  46.         console.log(index); 
  47.     } 
  48.     $scope.EditMovie = function (movie, index) { 
  49.         $scope.selectedRow = null;  // initialize our variable to null
  50.         $scope.selectedRow = index; 
  51.         $scope.movie = movie;         
  52.         $scope.edit = true; 
  53.     } 
  54. }]); 

Run your Application now and it should perform the actions. Once you run an Application, give the path of your desired page. It should look, as given below, in the screenshot. For now, the button will be working as anticipated.
output
Kindly open Movie.html page and find the given below line and understand its actual fact. Please refer below the screen, given below:
code
There are three major cases here as shown below:
First – Add button with + symbol
Second – Edit button with pencil symbol
Third - Cross with * Symbol.

Kindly find GIF image, given below, which performs all the actions. It will help you to understand the facts.

Hope this will help you some day. Enjoy coding.