【问题标题】:Interpolation in Angular JSAngular JS 中的插值
【发布时间】:2017-04-26 22:24:05
【问题描述】:

我正在尝试理解 Angular JS 中的插值概念,并且我已经编写了这段代码。我正在尝试在输入框中输入文本,并根据文本区域标签中的模板,它应该替换变量并在 previewText 字段中动态更新最终消息。如何做到这一点。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body ng-app="myApp">
<div ng-controller="MyController">
<input ng-model="to" 
      type="email" 
      placeholder="Recipient" />
<textarea ng-model="emailBody"></textarea>
<pre>{{ previewText }}</pre>
</div>
</body>
<script>
angular.module('myApp', []).controller('MyController',function($scope,   $interpolate) {
  $scope.to = 'text'; //static value.Trying to make this dynamic. How     to achieve it??
 //      $scope.$watch('to',function(newValue,oldValue,scope)
  //{
    //$scope.to = $interpolate($scope.to)($scope);
  //});
  $scope.emailBody = 'Hello {{ to }},My name is Ari too!';
  // Set up a watch
  $scope.$watch('emailBody', function(body) {
    if (body) {
      var template = $interpolate(body);
      $scope.previewText = 
        template({to: $scope.to});
    }
  });
  });



 </script>
 </html>

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-controller angularjs-watch angularjs-interpolate


    【解决方案1】:

    只需删除您的 $scope.watch 并将其替换为

    $scope.update = function() {
      $scope.previewText = $interpolate($scope.emailBody)($scope);
    };
    $scope.update();
    

    然后添加

    ng-change="update()"
    

    致您的&lt;input&gt;&lt;textarea>。

    请注意,由于您已指定&lt;input type="email"&gt;,因此to 模型仅在输入值为电子邮件地址时才有效并设置,不包括初始状态。

    http://plnkr.co/edit/AOR6a7TAYhoXYSnJh2r4?p=preview

    【讨论】:

    • 谢谢。那行得通:)您能否向我提供任何关于我可以更好地理解 Angular 中的插值概念的材料的建议?
    • @ang123 你似乎很了解他们。当to 模型更改时,您所缺少的只是一个更新previewText 的钩子
    【解决方案2】:

    AngularJS 使用嵌入表达式的插值标记来为文本节点和属性值提供数据绑定。

    插值示例如下:

    你好{{imagename}}!

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多