0

In this plnkr I'm attempting to programmatically build up an array of text values and display them within an an angular js view :

http://plnkr.co/edit/kOUKq9IuxE38QKAUSFJ1?p=preview

But the values are not being displayed. I think the issue is with this code :

var vp = [];
vp.push("Blue: true");

Is this the correct method building the array ? Shoud'nt this be correct serialized on json so that angularjs can display the values correctly ?

If I change :

var vp = [];
vp.push("Blue: true");

to

   var vp = {Blue: true, Orange: true};

It works correctly.

plnkr source :

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Multiple Checkboxes</title>
  <style>
    label {display: block;}
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
</head>

<body>
  <div ng:controller="MainCtrl">
    <label ng-repeat="(color,enabled) in colors">
        <input type="checkbox" ng-model="colors[color]"> {{color}} 
    </label>
    <p>colors: {{colors}}</p>

  <script>
    var app = angular.module('plunker', []);

    var vp = [];
    vp.push("Blue: true");

    app.controller('MainCtrl', function($scope){
        $scope.colors = vp;
    });
  </script>
</body>
</html>

Source of accepted answer :

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Multiple Checkboxes</title>
  <style>
    label {display: block;}
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
</head>

<body>
  <div ng:controller="MainCtrl">
<label ng-repeat="color in colors">
    <input type="checkbox" ng-model="color.enabled"> {{color.name}} 
</label>
    <p>colors: {{colors}}</p>

  <script>
    var app = angular.module('plunker', []);

    var vp = [];
    vp.push({name:'Blue', enabled:true});
    vp.push({name:'Black', enabled:true});


    app.controller('MainCtrl', function($scope){
        $scope.colors = vp;
    });
  </script>
</body>
</html>

http://plnkr.co/edit/S7SC6j5wJ7n8NsaRcaiW?p=preview

2 Answers 2

1

You are just adding a string to the array here:

var vp = [];
vp.push("Blue: true");

Usually, you bind to object literals, which follow the { property: x, property:b } syntax:

var vp = [];
vp.push( { Blue: true, NestedObject: { Color: 'Red'} });
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an alternative, adding objects to an indexed array instead of booleans to an associative array.

Javascript :

var vp = [];
vp.push({name:'Blue', enabled:true});

HTML :

<label ng-repeat="color in colors">
    <input type="checkbox" ng-model="color.enabled"> {{color.name}} 
</label>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.