AngularJS ng-model 指令用法

AgnularJS ng-model directive usage

为什么在下面的AngularJS example ng-model中使用指令?它可以在没有该指令的情况下工作——因为可以通过删除 ng-model 指令并将 myCol 变量设置为任何有效的背景颜色值来测试它。 ng-model 指令在这里有什么用?

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<p>Change the value of the input field:</p>

<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

<p>AngularJS resolves the expression and returns the result.</p>

<p>The background color of the input box will be whatever you write in the input field.</p>

</body>
</html>

ng-model 提供双向绑定,所以虽然 ng-init 设置了初始值,但如果你希望能够动态响应用户输入(通过输入改变颜色)那么你需要 ng-model .