AngularJS选择标签绑定

时间:2014-03-22 15:23:03

标签: javascript angularjs select

我正在尝试建立一个检查机制,其中运费价格根据国家/地区计算。如果用户选择美国,则应返回美国。如果用户选择任何其他国家/地区,则应返回“不是美国”

运输功能返回美国,因为选择选项位于美国。但是当另一个国家被选中时,该功能仍然会返回美国。

JS

var app = angular.module("CartApp", ['ngCookies']);
app.controller("CartForm", function ($scope, $cookieStore) {
    var shipping = 0;
    $scope.shipping = function () {
        var e = document.getElementById("countries").value;
        if (e == 'United States') {
            shipping = 1;
            return "US";
        } else if (e != 'United States') {
            shipping = 4;
            return "Not US";
        }
    };
});

HTML

<div ng-app="CartApp">
    <div ng-controller="CartForm">{{shipping()}}
        <select id="countries" name="countries">
            <option selected="selected" value="United States">United States</option>
            <option value="Albania">Albania</option>
            <option value="Algeria">Algeria</option>
        </select>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试混合两种不同的数据绑定机制。 刚刚拿起AngularJS,这似乎是相同的算法而不使用getElementById()

angular.module('demoApp', []).controller('DemoController', function ($scope) {
    $scope.countries = [ 'United States'
    , 
      'Albania'
    , 
      'Algeria'
    ];
    $scope.shipping = $scope.countries[0];
    $scope.isUS = function () {
        if ($scope.shipping == 'United States') {
            return 'US';
        } else {
            return 'Non US';
        }
    };
});


<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div>User selected: {{shipping}}</div>
        <div> Is US? {{isUS()}}</div>
        <select ng-model="shipping" ng-options="c for c in countries"></select>
    </div>
</body>