如何正确设置对象值?

时间:2017-06-09 21:45:17

标签: javascript angularjs

我只使用一个小型控制器,我有类似的东西:

<select ng-model="character" ng-options="ch.name for ch in characters"></select>

{{character}} <-- good, even {{character.attr}} works

{{attr}} <-- bad, not updated when select changes*


...function($scope){

$scope.character = characters[0]; <-- good, get/set object as spected

$scope.attr = $scope.character.name; <-- bad, it just sets an initial value*
                                         which is not updated when select does

}

$scope.attr = character.name, $scope.attr = $scope.character['name'],不起作用。所以这样的功能永远不会起作用:

$scope.attack_array = function(i){  <-- field or whole object cant be sent **
  let character = characters[i];
  let array..
}

$scope.attack_array($scope.character.index) <-- how do i get the separated values by each field?

1 个答案:

答案 0 :(得分:0)

将视图更改为此

<select ng-model="character" ng-init="character = characters[0]" ng-options="ch.name for ch in characters"></select>

您可以像$scope.attr = $scope.character.name;一样访问所选的值。 希望这会奏效。让我知道。如果你还想要别的什么。