lundi 11 juin 2018

AngularJS checbox--ngchecked and ng-repeat

i have go the following code:

 import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
   
 colors = ["Red", "Green", "Blue", "Yellow"]

  selectedColors = [];

  toggleColor (color) {
    if(this.isSelected(color)) {
      console.log("toggleColor: remove color " + color);
      this.selectedColors.splice(this.selectedColors.indexOf(color), 1);
    } else {
      console.log("toggleColor: add color " + color);
      this.selectedColors.push(color);
    }
  }

  $scope.isSelected = function(color) {
    return this.selectedColors.indexOf(color) > -1;
  }
  
  <div class="color" ng-repeat="color in colors">
  <label ng-click="toggleColor(color)">
    <input type="checkbox" ng-checked="isSelected(color)"/>

  </label>
</div>
<div>
  Selected: 
</div>
  
}

As an output I got nothing but "Selected:".

Then I tried with the following code

  import { Component, OnInit } from '@angular/core';



@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})


export class HomeComponent implements OnInit {
  
  colors = ["Red", "Green", "Blue", "Yellow"]

  selectedColor() {
    console.log("test test test the function!");
  }
}
<div >
  <label for="color">color:</label>
  <div *ngFor="let color of colors">
    <label>
      <input type="checkbox"
             name="color"
             ngModel="color"
             value=""
             ng-checked="selectedColor()"
      >
      
    </label>
  </div>
</div>

With this code I can see the checkboxes--all checked which I guess it has to do with the ng-moded. I realized: 1- that my function selectedColor does not trigger, and 2- Without parenthesis around 'ng-checked' here : ng-checked="selectedColor()", my function is not recognized. with the parenthesis, the output is the same, though.

Sorry if the question seems trivial to some of you, I am new to coding so it may justify it.

please help me understand how it should be. I am using the following: Angular CLI: 6.0.7 Node: 10.0.0 OS: win32 x64 Angular: 6.0.3

Thanks.




Aucun commentaire:

Enregistrer un commentaire