使用AngularJS将模型变量从控制器传递到html

时间:2015-06-19 10:03:14

标签: angularjs angularjs-controller

我对AngularJs很新。在我的例子中,我试图通过使用AngularJs标记从控制器模型读取两个initiger值,并在html页面中读取多个数字。

控制器

(function (angular) {
angular.module('Invoice1', [])
.controller('InvoiceController', function () {
    this.qty = 1;
    this.cost = 2;
  });
})

HTML

<!DOCTYPE html>
<html ng-app>
<head>
 <title>AngularJs Form Test 2</title>
 <link href="Content/bootstrap.min.css" rel="stylesheet" />
 <script src="Scripts/angular.min.js"></script>

<script src="invController.js"></script>
</head>
 <body>
  <div id="calculateNumber" ng-app="Invoice1" ng-controller="InvoiceController as invoice">
    <div>
        Quantity : <input type="number" min="0" ng-model="invoice.qty" />
    </div>
    <div>
        Costs : <input type="number" min="0" ng-model="invoice.cost" />
    </div>
    <div>
        <b>Total: </b> {{invoice.qty * invoice.cost | currency}}
    </div>
  </div>
 </body>
</html>

2 个答案:

答案 0 :(得分:2)

您在html中提到了多个ng-app

ng-app="Invoice1"标记中使用<html>,删除另一个,您就可以了

<!DOCTYPE html>
<html ng-app="Invoice1">
<head>
 <title>AngularJs Form Test 2</title>
 <link href="Content/bootstrap.min.css" rel="stylesheet" />
 <script src="Scripts/angular.min.js"></script>

<script src="invController.js"></script>
</head>
 <body>
  <div id="calculateNumber" ng-controller="InvoiceController as invoice">
    <div>
        Quantity : <input type="number" min="0" ng-model="invoice.qty" />
    </div>
    <div>
        Costs : <input type="number" min="0" ng-model="invoice.cost" />
    </div>
    <div>
        <b>Total: </b> {{invoice.qty * invoice.cost | currency}}
    </div>
  </div>
 </body>
</html>

这是更新后的plunkr

答案 1 :(得分:0)

我已设法通过将控制器javaScript代码更改为

来运行它
var myApp2 = angular.module('Invoice1', []);

myApp2.controller('InvoiceController', function ($scope) {
   $scope.qty = 1;
   $scope.cost = 2;
});