AngularJS如何设置绑定元素的动态值

时间:2016-09-27 10:38:18

标签: javascript angularjs binding

我需要根据页面变量中的来更改绑定元素的值。

这是页面var:

<select value="">
 <option ng-repeat="value in valueList">
  {{myNewValue()}}
 </option>
</select>

这是带有bind元素的select:

$scope.inPageVar = $window.myVar;

$http.get(jsonUrl).then(function(result) {
    $scope.valueList = result.data.valueList;
    $scope.myNewValue = function() {
      return $scope.valueList[0].additional + $scope.inPageVar;
    };
});

这是控制器:

"valueList": [
          {
            "additionnal": {
              "value1": "this is value 1",
              "value2": "this is value 2"
            }
          },
          {
            "additionnal": {
              "value1": "this is value 3",
              "value2": "this is value 4"
            }
          }
        ]

这里是JSON结构:

^(?=.*[1-9])\d{1,10}$

我想知道如何将页内var值与get函数的元素连接起来。谢谢!

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
(function() {

  angular.module("CombineModule", []).controller('MyController', function() {
    this.values = [{
      "additional": {
        "value1": "this is value 1",
        "value2": "this is value 2"
      }
    }, {
      "additional": {
        "value1": "this is value 3",
        "value2": "this is value 4"
      }
    }];

    this.myNewValue = function(index) {
      return this.values[index].additional[myVar];
    };
  });

})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="CombineModule">

<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script>
    var myVar = 'value1';
  </script>
</head>

<body ng-controller="MyController as v">
  <select value="">
    <option ng-repeat="value in v.values">
      {{v.myNewValue($index)}}
    </option>
  </select>
  <script src="app.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

如果您想全局公开myVar,

window.myVar = 'some value'而不是var myVar = 'someval'

或者,如果您想将其提供给$rootScope.myVar = 'some value'

然后在你的逻辑中,

return $scope.valueList[0].additional[window.myVar];