Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ng-controller in AngularJS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 239
    Comment on it

    Controllers in AngularJS are the JavaScript object that consist of properties and functions. Controller's main objective is to defines the flow of data in the application. In AngularJS we define controller using ng-controller directive. Whenever a Controller is linked to any DOM by ng-controller directive, AngularJS will instantiate a new Controller object, using the specified controller's constructor function. In this controller constructor an injectable parameter $scope would be available as a parameter.

    Whenever a new application is created we need to set up the initial state for the $scope by attaching properties to the to the $scope object.And for that we use controllers in AngularJS.
    For Example:
     

    <div ng-app="myApp" ng-controller="WelcomeController">
      {{ greeting }}
    </div>
    
    <script>
    
    var myApp = angular.module('myApp',[]);
    
    myApp.controller('WelcomeController', ['$scope', function($scope) {
      $scope.greeting = 'Hello World';
    }]);
    </script>

    In the example above we have seen that $scope properties would be available to the template.

    The other use controller is to add behavior to the $scope object.We can add behavior by attaching methods to the $scope object. These methods are then available in the view.

    The following example uses a Controller to add a method to the scope which display the full name:

    <div ng-app="myApp" ng-controller="homeController">
    
    Enter first Name: <input type="text" ng-model="firstName"><br>
    Enter Last Name: <input type="text" ng-model="lastName"><br>
    <br>
    Full Name: {{fullName()}}
    
    </div>
    
    <script>
    var app = angular.module('myApp', []);
    app.controller('homeController', function($scope) {
        $scope.firstName = "John";
        $scope.lastName = "Doe";
        $scope.fullName = function() {
            return $scope.firstName + " " + $scope.lastName;
        };
    });
    </script>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: