2017-07-31 71 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