Angular2 / Javascript - 检索在for循环中生成的变量的新值

时间:2016-05-02 17:53:35

标签: javascript angular

我愿意检索在for循环中更新的变量的值,并在范围之外访问它。

为此,我有: 的 page.html中

<div [options]="Pages">
  <div *ngFor="#cat of category">
        <div class="newCategory">The new category will appear here!</div>
  <div>
</div>

Page.js

constructor(viewCtrl, http, navParams) {
   this.viewCtrl  = viewCtrl;
   this.navParams = navParams;
   this.http      = http;
   this.category  = null; 

   this.http.get('https://website.com/api', { search }).subscribe(data => {
     this.category = data.json().results; 
   }); 

  //I want to print the new value of 'this.category' here
  //e.g: console.log(this.category); 

  this.Pages = {
    pagination: '.swiper-pagination',
    slidesPerView: 1,
    paginationClickable: true,
    paginationBulletRender: function (index, className) { 
     //also I want to access it here  
     return '<span class="' + className + '">' + this.category[index+1] + '</span>';
    }
  }
}

我是否需要有一个全局变量才能读取变量的新值?或者我还需要其他东西吗?

2 个答案:

答案 0 :(得分:1)

不确定问题是什么。一个猜测:

 <div class="newCategory">{{cat}}</div>

需要更改构造函数

constructor(viewCtrl, http, navParams) {
        this.viewCtrl = viewCtrl;
        this.navParams = navParams;
        this.http = http;
        this.category = null;

        this.http.get('https://website.com/api', { search }).subscribe(data => {
        this.category = data.json().results;
       //I want to print the new value of 'this.category' here
       //e.g: console.log(this.category);


              this.Pages = {
            pagination: '.swiper-pagination',
            slidesPerView: 1,
            paginationClickable: true,
           paginationBulletRender: function (index, className) {


           //also I want to access it here 


           return '<span class="' + className + '">' + this.category[index+1] + '</span>';
            }
            }


        });
      }

答案 1 :(得分:1)

最好的方法是存储this.category并将其循环到数组中,然后您就可以获得this.http.get()

之外的存储值