在 AngularJS 中添加变量

Addition of variables in AngularJS

本文关键字:变量 添加 AngularJS      更新时间:2023-09-26

我正在尝试获取一个按钮将 3 个单独的变量添加在一起,但它似乎不起作用:

这是JS:

angular.module('basket', ['onsen'])
.controller('basketController', function() {
  this.topsQuantity = 1;
  this.bottomsQuantity = 2;
  this.underwearQuantity = 3;
  this.calculator = 0;
  this.pay = function pay() {
    window.alert("Thanks!");
  };
  this.total = function calculator(topsQuantity, bottomsQuantity, underwearQuantity) {
    return topsQuantity + bottomsQuantity + underwearQuantity;
  };
});

这是 HTML:

<label ng-model="basket.total">Total: {{basket.total}}</label>
        <div  style="width: 100% !important; position: fixed; bottom: 10px;">
          <ons-button modifier="cta" onclick="basket.total">
          <!--<ons-button modifier="cta" onclick="myNavigator.pushPage('Laundries.html', { animation : 'slide' } )">-->
            Calculate Total <ons-icon icon="fa-angle-right"></ons-icon>
          </ons-button>
        </div>

任何帮助将不胜感激!

你的代码中有各种各样的错误:

  1. 你最好理解这个和$scope在AngularJS上下文中的区别。

这。javascript 中的 [propertyName] 是对象内部名为 [propertName] 的属性的声明。

在 AngularJS 中 - $scope是一个成员,您应该在其中声明您在模板(您的 html)中使用的所有变量。

  1. 如果声明控制器,则无法在代码中看到,期待某处:

    ng-controller='basketController'

  2. 您将模块命名为"篮子",并在 HTML 中使用变量"篮子"(尽管它没有在控制器中声明) - 您应该在$scope上贴花。

所以在你的情况下,它应该是:

angular.module('basket', ['onsen'])
   .controller('basketController', function() {
       this.topsQuantity = 1;
       this.bottomsQuantity = 2;
       this.underwearQuantity = 3;
       this.calculator = 0;
       this.pay = function pay() {
           window.alert("Thanks!");
       };
       $scope.total = function calculator(topsQuantity, bottomsQuantity, underwearQuantity) {
           return topsQuantity + bottomsQuantity + underwearQuantity;
       };
   });

(注意$scope.总计)

你的 HTML 应该是这样的:

<label>Total: {{total()}}</label>