如何使用angularjs在控制器中获取选定的值

时间:2017-07-27 11:07:12

标签: javascript angularjs

我是angularjs的新手并试图在控制器中获取所选值。它在前端工作正常但是控制器中的选定值未定义,如何在控制器中访问所选值?

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

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


        <select ng-change="changed()" ng-model="selectedOption" class="form-control">
            <option ng-repeat="x in options" value="{{x.reason}}">{{x.reason}}</option>
        </select>
        {{selectedOption}}

    </div>


    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.options = [{reason: "Facebook"},
                {reason: "Instagram"},
                {reason: "Google"},
                {reason: "Twitter"},
                {reason: "SMS"}];
            $scope.changed = function () {
                console.log("selected Options: " + $scope.selectedOption);
            }
        });
    </script>

</body>

</html>

4 个答案:

答案 0 :(得分:0)

您的代码有效。

<强>样本

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.options = [
   {reason : "Facebook"},
   {reason : "Instagram"},
   {reason : "Google"},
   {reason : "Twitter"},
   {reason : "SMS"},

];
$scope.changed= function() {
   console.log("selected Options: "+$scope.selectedOption);
}
});
<!DOCTYPE html>
<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-change="changed()" ng-model="selectedOption" class="form-control">
<option ng-repeat="x in options" value="{{x.reason}}">{{x.reason}}</option>
</select>{{selectedOption}}
</div>

答案 1 :(得分:0)

似乎一切正常,只需从控制器的任何地方拨打$scope.selectedOption即可。

答案 2 :(得分:0)

它的工作完美!我在JSFiddle中试过这个,它应该正常工作!

即使这样也有效。

$scope.changed= function() {
   console.log("selected Options: "+$scope.selectedOption);
}

请看这里:https://jsfiddle.net/vLam3pe0/

答案 3 :(得分:0)

<script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
        $scope.selectedOption;
            $scope.options = [{reason: "Facebook"},
                {reason: "Instagram"},
                {reason: "Google"},
                {reason: "Twitter"},
                {reason: "SMS"}];
            $scope.changed = function () {
                console.log("selected Options: " + $scope.selectedOption);
            }
        });
    </script>