Angular JS – Controller Initialization

There are cases in which you need to pass some parameter to the controller from outside. For these cases is possible to define the $scope.init() function, which can be called at the controller initialization with the ng-init directive.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Angular JS</title>
</head>
<body data-ng-app="myApp">
    <div data-ng-controller="myController" data-ng-init="init('Frank', 'Zappa')">
        <p>The full name is {{ firstName + " " + lastName }}</p>
    </div>
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
 
    <script>
        angular.module("myApp", ["myApp.controllers"]);
 
        angular.module("myApp.controllers", []).controller("myController", function ($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
 
            $scope.init = function (firstName, lastName) {
                $scope.firstName = firstName;
                $scope.lastName = lastName;
            };
        });
    </script>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s