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="">
    <title>Angular JS</title>
<body data-ng-app="myApp">
    <div data-ng-controller="myController" data-ng-init="init('Frank', 'Zappa')">
        <p>The full name is {{ firstName + " " + lastName }}</p>
    <script src="//"></script>
    <script src="//"></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;

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s