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?

0

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

ok dat works....but just to know why it doesn't pick up data from value attr of input element on page load
@iBlue - Just because that's the way it works. The data belongs in the model, not in the view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.