ng模型和角度表达之间的差异 - {{}}

时间:2016-08-18 05:37:28

标签: javascript html angularjs

{{}}工作正常,但ng-model不在同一个地方。

我正在使用以下html -

<body ng-app="crud">
  Gray input fields will not be visible.
  <div ng-controller="ctrl">
    <input type="text" value="sdf" ng-model="asdf"/>
    <h1 ng-model="asdf"></h1>   <!-- this doesn't work-->
    <h1>{{asdf}}</h1>           <!-- this work-->
    </div>
  </div>
</body>

asdf在这个js应用程序中定义如下

 var app = angular.module("crud", []);
 app.controller("ctrl", ['$scope', function($scope) {
     $scope.asdf="ankur";
 }]);

有人可以解释为什么会这样吗?

5 个答案:

答案 0 :(得分:5)

ng-model指令用于输入字段,例如输入,选择双向数据绑定以及从用户获取输入。

单向数据绑定表达式{{}}或ng-bind指令用于在视图中输出数据。

&#13;
&#13;
var app = angular.module("crud", []);
app.controller("ctrl", ['$scope', function($scope) {
    $scope.asdf="ankur";
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="crud">
  Gray input fields will not be visible.
  <div ng-controller="ctrl">
    <input type="text" value="sdf" ng-model="asdf"/>
    <h1 ng-bind="asdf"></h1>
    <h1>{{asdf}}</h1>
  </div>
</div>
  
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用ng-bind进行显示,而不是ng-model

<h1 ng-bind="asdf"></h1>

您只想在绑定到将要编辑变量的元素时使用ng-model,例如文本字段。

答案 2 :(得分:0)

来自documentation

  

ngModel指令使用NgModelControllerinputselecttextarea(或自定义表单控件)绑定到作用域上的属性,这是由该指令创建和公开。

您正试图在<h1>上使用它。请改用ng-bind

答案 3 :(得分:0)

根据文件

the ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

所以你不会用它来显示H1

对于括号,即使没有必要,也会在每个$摘要中对它们进行脏检查和刷新。所以它慢了。当你的angularjs引导时,可能会出现thez

答案 4 :(得分:0)

ng-model :此指令将AngularJS应用程序数据的值绑定到HTML输入控件。

{{}} 此用途仅用于打印目的。你可以把表达式也像{{2 * 2}}那样打印4

请参阅此研究基本语法https://angularjs.org/

相关问题