0

我是 AngularJS 的新手,只是在玩这些东西。这是我的 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" />

这是控制器代码:

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

我已经使用属性设置了输入文本字段的值value。所以我希望控制器函数getFullName能够读取这些值并在页面加载时返回全名。但我得到的是:

undefined undefined

并且输入文本框为空。为什么会这样?

4

1 回答 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>
于 2013-06-26T08:40:29.483 回答