Angular JS - 嵌套模板(双花括号{{}})

时间:2016-07-21 20:43:37

标签: javascript angularjs

有没有办法嵌套角度模板?

例如具有以下变量:

$scope.myVar = 'hello {{name}}, you weigh {{weight}}'
$scope.name = '';
$scope.weight = '';

让html文件看起来像:

<h1>{{myVar}}</h1>
<div>
    Your Name:
    <input ng-model="name" type="text">
</div>
<div>
    Your Weight:
    <input ng-model="weight" type="text">
</div>

然后让角度从myVar动态设置名称和权重模板?

3 个答案:

答案 0 :(得分:5)

我认为你所寻找的是毫无意义的。您可以定义如下所示的函数,然后在标题中调用此函数。

$scope.myVar = function() {
    return 'hello ' + $scope.name + ' you weigh '+ $scope.weight;
}

var app = angular.module('app',[]);
app.controller('mainController',['$scope', function($scope){
    $scope.name = "test";
    $scope.weight = 100;
    $scope.myVar = function() { return 'hello ' + $scope.name + ' you weigh ' + $scope.weight; };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="mainController">
      <h1>{{myVar()}}</h1>
        <div>
          Your Name:
          <input ng-model="name" type="text"/>
        </div>
        <br/>
        <div>
          Your Weight:
          <input ng-model="weight" type="text"/>
        </div>
    </div>
  </body>
 </html>

答案 1 :(得分:0)

我最终意识到我遇到了范围错误。所以,为了解决绑定错误,我使用了$ interpolate。请参阅:How to evaluate angularjs expression inside another expression

答案 2 :(得分:0)

当然你会这样做:

<h1>Hello {{name}} you weigh {{weight}}</h1>
<div>
    Your Name:
    <input ng-model="name" type="text">
</div>
<div>
    Your Weight:
    <input ng-model="weight" type="text">
</div>