2017-07-31 70 views
-2

所以我有一个使用AngularJS的webapp。我想将它改为使用Angular 2(使用TypeScript代替Javascript)。我很难得到以下部分,因为我不知道角度等值是什么。任何帮助将不胜感激。最主要的是我该如何处理与我的新数组this.books一起使用的$ scope部分。AngularJS的Angular 2

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; 
} 
+0

角和AngularJS是*同样的事情* – Amy

+0

在2014年,谷歌宣布角2.据更名和重新利用。 JavaScript的'JS'字母从其品牌中删除,因为TypeScript成为它的首选方言。 – user121168

+0

我知道产品被重新命名。然后改变你的问题,说你正在从Angular 1改变到Angular 2.正如你所写的,你正在从Angular改为Angular,这是没有意义的。 – Amy

回答

1

Angular JS和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; 
    } 
} 
+0

*没有控制器*,你是错误的队友,组件类是控制器,模板是视图,控制器+模板=组件 – Dummy

+2

我的意思是没有像角1中的控制器。他是角2中的新人,这就是为什么我已经像那个哥们一样回答了@Dummy –

+0

好吧,原谅! – Dummy