【问题标题】:Angular 2 from AngularJS来自 AngularJS 的 Angular 2
【发布时间】:2018-01-07 08:35:50
【问题描述】:

所以我有一个使用 AngularJS 的 webapp。我想将其更改为使用 Angular 2(使用 TypeScript 而不是 Javascript。)。我正在努力获得以下部分,因为我不知道 Angular 等价物是什么。任何帮助将不胜感激。主要是我如何处理与我的新数组 this.books 一起使用的 $scope 部分。

function CartController($scope) {
var store = null;
if(typeof(Storage) !== "undefined") {
    var store = localStorage.getItem("lastName_cart");
}
if(store != null) {
    $scope.books = JSON.parse(store);
} else {
$scope.books = 
[{ title: 'Absolute Java', qty: 1, price: 114.95},
 { title: 'Pro HTML5', qty: 1, price: 27.95},
 { title: 'Head First HTML5', qty: 1, price: 27.89}];
} 
 $scope.total = 114.95 + 27.95 + 27.89;


$scope.removeBook = function(index) {
    $scope.books.splice(index, 1);
    $scope.updateTotal();
}

$scope.updateTotal = function() {
    var sum = 0;
    for (var i = 0; i < $scope.books.length; i++) {
        sum += $scope.books[i].price * $scope.books[i].qty; 
    }
    $scope.total = sum;
}

【问题讨论】:

  • Angular 和 AngularJS 是相同的东西
  • 2014 年,Google 发布了 Angular 2。它被重新命名并重新定位。 JavaScript 的“JS”字母已从其品牌中删除,因为 TypeScript 成为其首选方言。
  • 我知道该产品已重命名。然后将您的问题更改为说您正在从 Angular 1 更改为 Angular 2。正如所写的那样,您正在从 Angular 更改为 Angular,这没有任何意义.
  • 我在做更多研究时才意识到 AngularJS 也被称为 Angular 1。抱歉,现在已修复。
  • 我参加了聚会,直接进入了 Angular 4。所以我对 AngularJS 不是很熟悉。我认为您已经仔细阅读过:angular.io/guide/upgradeangular.io/guide/ajs-quick-reference - 我记得当我开始学习时看到过。希望能给你带来你想要的…… bindToController: {}。组件输入和输出应该绑定到控制器,而不是使用 $scope。

标签: javascript angularjs html angular


【解决方案1】:
【解决方案2】:

Angular JS 和 Angular 完全不同。 角度使用打字稿,它是基于组件的。没有控制器。

你的代码在 angular 2 或 4 中应该是这样的

import { Component } from '@angular/core';
  @Component({
      selector: 'app-cart',
      templateUrl: './cart.component.html'
   })
  export class CartComponent {
       store = null;
       book = [];
       total: Number;
 constructor() {
        if(typeof(Storage) !== "undefined") {
            this.store = localStorage.getItem("lastName_cart");
        }
       if(this.store != null) {
         this.books = JSON.parse(store);
       } else {
           this.books = 
              [{ title: 'Absolute Java', qty: 1, price: 114.95},
              { title: 'Pro HTML5', qty: 1, price: 27.95},
              { title: 'Head First HTML5', qty: 1, price: 27.89}];
          } 
       this.total = 114.95 + 27.95 + 27.89;
     }
   removeBook(index) {
      this.books.splice(index, 1);
      this.updateTotal();
   }
   updateTotal() {
     let sum = 0;
     for (let i = 0; i < this.books.length; i++) {
       sum += this.books[i].price * this.books[i].qty; 
     }
    this.total = sum;
   }
 }

【讨论】:

  • 没有控制器,你错了,组件类是控制器,模板是视图,控制器+模板=组件
  • 我的意思是没有像 angular 1 那样的控制器。他是 Angular 2 的新手,这就是为什么我会像那个哥们 @Dummy 那样回答
猜你喜欢
  • 2018-10-03
  • 2017-10-12
  • 2023-04-09
  • 2019-04-02
  • 2023-03-15
  • 2016-08-01
  • 2017-02-14
  • 2018-03-17
  • 1970-01-01
相关资源
最近更新 更多