Method in AngularJS Example


        In this tutorial lets see how to define and invoke a AngularJS method from html. Methods help us to reuse functionality across your HTML code. So we are going to input two fields from the UI, append both in the method and display it back.

Pls have a background of MVC in AngularJS if you are not sure.. Because we will use MVC pattern in this tutorial.

Step 1 : Add input Field to HTML
<input type ="text" ng-model ="Value.text1">
<input type ="text" ng-model ="Value.text2">

Step 2 : Add Controller and Function
      <script>
         var mainApp = angular.module("myApp", []);
         
         mainApp.controller('mycontroller', function($scope) {
            $scope.Value = {
               text1: "",
               text2: "",
           
               AppendedValue: function() {
                  var ValueObj;
                  ValueObj = $scope.Value;
                  return ValueObj.text1 + " " + ValueObj.text2;
               }
            };
         });
      </script>


Here we have defined a controller "mycontroller" with $scope, with a method named "AppendedValue". Now this method with append the input values text1 and text2

Step 3 : Display value returned from Method
 <p> {{Value.AppendedValue()}} </p>

We have invoked the method from <p> tag. Now this function can be used anywhere in your program. 

Program

<html>
   
   <head>
      <title>Angular JS Function</title>
      <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
      
   </head>
   <body>
      <h2>AngularJS Function</h2>
      <div ng-app ="myApp" ng-controller ="mycontroller">
         
         <input type ="text" ng-model ="Value.text1">
         <input type ="text" ng-model ="Value.text2">
         
    <p> {{Value.AppendedValue()}} </p>
      </div>
      
      <script>
         var mainApp = angular.module("myApp", []);
         
         mainApp.controller('mycontroller', function($scope) {
            $scope.Value = {
               text1: "",
               text2: "",
           
               AppendedValue: function() {
                  var ValueObj;
                  ValueObj = $scope.Value;
                  return ValueObj.text1 + " " + ValueObj.text2;
               }
            };
         });
      </script>
      
   </body>
</html>

Output:


Hope this tutorials help you understand - how to call AngularJS method from HTML..




Reactions:

0 comments :

Post a Comment