angular material 带有对象数组的 md-switch

angular material md-switch with array of objects

好吧,我正在使用 Angular Material 开关进行切换,但它并没有像您在图片上看到的那样从初始状态开始。旁边的标签就是它的价值。

如您所见,开关从一开始就处于停用状态。

首先,我从 get 请求中获取结果,并将其放入一个数组中。

$scope.questions = [];

我在图片上显示的值可能是假的也可能是真的。 在 md-switch 上,我直接引用了数组内部的 属性。

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

如何设置开关的初始值?

这是一个带测试的Codepen。 http://codepen.io/anon/pen/BjzpNN

但这看起来很尴尬。做我的例子它工作正常,但在我的开发环境中,它不起作用。 这是我数组的 console.log,我使用 $resource.

将其作为获取请求获取

嗯,有什么问题吗?

编辑2: 更尴尬的是,使用属性 ng-true-value 和 ng-false-value 开关不会获得初始状态。

我在下方更新了您的 JavaScript,以使用服务获取结果。但是,我只是 return 从您的示例中提取硬编码数据。您应该更改服务以获取数据。该服务将用作承诺,完成后将 return。

(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.
    }]);
}())

不检查数据加载,因此在服务 returns 数据之前您的屏幕将是空白的。但是,当服务 returns 数据时,您的视图应该更新。

正如您的 CodePen 所示,您不需要 ng-true-value/ng-false-value,只需要 ng-model 来列出要从中获取设置的字段。 ng-true-value 是当你切换开关时要设置的值(Angular md-switch docs 如果你想要不同于 True/False 的东西(比如 A/B)。

如果您想防止开关发生变化,您可能还需要使用 ng-disabled。