Matheus Silva Matheus Silva - 4 months ago 11
AngularJS Question

angular material md-switch with array of objects

Well, I'm making a switch using Angular Material switch, but it's not starting with its initial state as you can see on the picture. The label aside it is the value of it.

enter image description here

And as you can see, the switch starts deactivated from the beginning.

To Start, I'm getting the results from a get request, and putting it into an array.

$scope.questions = [];


The value I'm showing on the picture can be false or true.
On the
md-switch
, I've referenced directly to the property inside of the array.

<tr ng-repeat="quest in questions">
<td><md-switch ng-model="quest.status">{{quest.status}}</md-switch></td>
</tr>


How can I set the value initially for the switch?

This is a Codepen with a test.
http://codepen.io/anon/pen/BjzpNN

but this seems awkward tho. Doing my example it works fine, but with my development environment, it doesn't work.
This is the console.log of my array, I'm getting this as a get request using
$resource
.

Well, what is the problem?

Edit2:
Even more awkward, using the properties ng-true-value and ng-false-value the switch doesn't get the initial state.
enter image description here

Answer

I updated your JavaScript below, to use a service to get the results. However, I am just returning the hard coded data from your sample. You should change the service to go and fetch your data. The service will be used as a promise, and will return when complete.

(function(){
    var app = angular.module('test', ['ngMaterial'])
    .service('testService', function() {
    // This should be modifed to then call your external API to get the data instead of hard coded results
        var questions = [
            { name : "teste",  status : true},
            { name : "teste2", status : false},
            { name : "teste3", status : true}
        ];
        return questions;    
    })
    .controller('testController', ['$scope', 'testService', function($scope, testService) {
        $scope.questions = [];

        $scope.questions = testService;     // Use service to get data, will update questions when promise returns.
    }]);
}())

There is no check on the data loading, so your screen will be empty until the service returns data. However, when the service returns data, your view should be updated.

As your CodePen showed, you do not need the ng-true-value/ng-false-value, just the ng-model to list the field to get the setting from. The ng-true-value is the value to be set when you toggle the switch (Angular md-switch docs if you want something different from True/False (say A/B).

You might also need to use ng-disabled if you want to protect the switches from changing.