为什么Angular中的一元加法工作没有?

时间:2015-01-12 17:04:16

标签: angularjs

为什么+ =一元运算符不能在以下代码中附加模型数据?

HTML:

<div ng-app="app">
<div   ng-controller="con1">
    <input ng-model="mydata"/>
    <br/>
    {{ mydata }}
</div>
</div>

角:

var app = angular.module("app", []);
app.controller("con1", function($scope) {
    $scope.mydata += $scope.mydata;
});

示例:http://jsfiddle.net/e41rzu9c/1/

我期待的输出:

type into text box: h
output: h
type into text box: e
output: hhe
type into text box: l
output: hhehhel
type into text box: l
output: hhehhelhhehhell

换句话说,它应该将输入与先前的输入连接起来吗?

[更新:按照Davin Tyron的回答解决NaN问题] 另外,如何初始化模型以便NaN不显示?我尝试在输入字段中添加ng-init =“”但没有效果。

1 个答案:

答案 0 :(得分:2)

由于双向数据绑定,您可能会陷入无限循环。从幕后开始,Angular希望在字段更改时更新模型,在模型更改时更新字段。必须有一些东西可以打破它的工作循环。试试这个:

HTML:

<div ng-app="app">
    <div   ng-controller="con1">
        <input ng-model="inputVal" ng-change="updateField()" />
        <br/>
        {{ mydata }}
    </div>
</div>

控制器:

var app = angular.module("app", []);
app.controller("con1", function($scope) {
    $scope.inputVal = '';
    $scope.mydata = '';
    $scope.updateField = function() {
        $scope.mydata += $scope.inputVal;
    };
});

现在,您更新的变量不会绑定到您键入的位置,因此它只会在您实际键入时更新,而不会在值更改时更新。