为什么AngularJs中的ng-model没有选择值?

时间:2017-06-19 07:37:28

标签: javascript html angularjs

我有角度的这个数组:

$scope.skins = [
    { code : "default", name : "DEFAULT_TXT" },
    { code : "aero", name : "AERO_TXT" },
    { code : "navy", name : "NAVY_TXT" },
    { code : "facebook", name : "FACEBOOK_TXT" },
    { code : "turquoise", name : "TURQUOISE_TXT" },
    { code : "lime", name : "LIME_TXT" },
    { code : "green", name : "GREEN_TXT" },
    { code : "purple", name : "PURPLE_TXT" },
    { code : "white", name : "WHITE_TXT" },
    { code : "concrete", name : "CONCRETE_TXT" },
    { code : "watermelon", name : "WATERMELON_TXT" },
    { code : "lemonade", name : "LEMONADE_TXT" }
]

我已经用ng-options创建了一个选择选项。我已经将ng-model设置为某个值,但它没有选择它。我做错了什么?

以下是完整示例JSFiddle

4 个答案:

答案 0 :(得分:3)

应该是这样的

$scope.opts = {};

并删除track by ...

Demo

答案 1 :(得分:2)

因为ng-model绑定到列表中的对象,而不是'代码'属性,请尝试使用此javascript代码。

app = angular.module("myApp", []);

app.controller('myCtrl', function ($scope, $http) {
    var defSkin = { code: "white", name: "WHITE_TXT" };
    $scope.skins = [
        { code: "default", name: "DEFAULT_TXT" },
        { code: "aero", name: "AERO_TXT" },
        { code: "navy", name: "NAVY_TXT" },
        { code: "facebook", name: "FACEBOOK_TXT" },
        { code: "turquoise", name: "TURQUOISE_TXT" },
        { code: "lime", name: "LIME_TXT" },
        { code: "green", name: "GREEN_TXT" },
        { code: "purple", name: "PURPLE_TXT" },
        defSkin,
        { code: "concrete", name: "CONCRETE_TXT" },
        { code: "watermelon", name: "WATERMELON_TXT" },
        { code: "lemonade", name: "LEMONADE_TXT" }
    ]

    $scope.opts = [];
    $scope.opts.sidebarSkin = defSkin;

});

答案 2 :(得分:1)

$ scope.opts是一个不是数组的对象,

$scope.opts = {};

<强> DEMO

答案 3 :(得分:0)

您可以使用 ng-selected 来选择特定值。demo

<div ng-app="myApp">
      <div ng-controller="myCtrl">

        <select class="form-control" ng-model="opts.sidebarSkin" name="sidebarTemplate" ng-options="skin.code as skin.name  for skin in skins" ng-selected="code == opts.sidebarSkin">

        </select>
      </div>
    </div>

Angular Js Code

app = angular.module("myApp", []);

app.controller('myCtrl', function($scope, $http) {

      $scope.skins = [
        { code : "default", name : "DEFAULT_TXT" },
        { code : "aero", name : "AERO_TXT" },
        { code : "navy", name : "NAVY_TXT" },
        { code : "facebook", name : "FACEBOOK_TXT" },
        { code : "turquoise", name : "TURQUOISE_TXT" },
        { code : "lime", name : "LIME_TXT" },
        { code : "green", name : "GREEN_TXT" },
        { code : "purple", name : "PURPLE_TXT" },
        { code : "white", name : "WHITE_TXT" },
        { code : "concrete", name : "CONCRETE_TXT" },
        { code : "watermelon", name : "WATERMELON_TXT" },
        { code : "lemonade", name : "LEMONADE_TXT" }
      ]

      $scope.opts = {};
      $scope.opts.sidebarSkin = "white";

    });