0

I'm new to AngularJS and was just playing around with the stuff. Here is my HTML:

<div ng-app ng-controller="nameController">
    <input type="text"  value="Jack" ng-model="fname" />
    <input type="text" value="Sparrow" ng-model="lname" />
    {{getFullName()}}
</div>

<input type="text" value="Hello" />

And here is the controller code:

function nameController($scope) {
    $scope.getFullName = function () {
        return $scope.fname + " " + $scope.lname;
    };
}

I have set the value of the input text fields using the value attribute. So I expected the controller function getFullName to read those values and return the full name on page load. But what I get is:

undefined undefined

And the input text boxes empty. Why is it so?

James Allardice
  • 164,175
  • 21
  • 332
  • 312
iJade
  • 23,144
  • 56
  • 154
  • 243

1 Answers1

1

If you want default values for those inputs, use the model and set them as properties on $scope in the controller:

function nameController($scope) {
    $scope.fname = "Jack";
    $scope.lname = "Sparrow";
    $scope.getFullName = function () {
        return $scope.fname + " " + $scope.lname;
    };
}

You can then remove the value attribute from the markup. This keeps the data nicely separated from the view. Here's a working example.

Alternatively, you could use the ngInit directive:

<div ng-app ng-controller="nameController" ng-init="fname = 'Jack'; lname = 'Sparrow'">
    <input type="text" ng-model="fname" />
    <input type="text" ng-model="lname" />
    {{getFullName()}}
</div>
James Allardice
  • 164,175
  • 21
  • 332
  • 312