AngularJS选择OnChange结果未反映在附加模型中

时间:2015-01-22 12:20:41

标签: angularjs

我的指令中有以下标记:

<select class="form-control" 
ng-change="changeLanguage()" 
ng-model="selectedLanguage" 
ng-options='lang.key as lang.name for lang in languages'></select>
<p>{{selectedLanguage}}</p>

我的指令控制器相关部分是:

$scope.languages = [{
    name: "Java",
    key: "java",
}, {
    name: "C",
    key: "c",
}];

$scope.$watch("selectedLanguage", function(newValue, oldValue) {
    console.log("watch", newValue, oldValue);
});

$scope.changeLanguage = function() {
    console.log("language changed: " + $scope.selectedLanguage)
}

但是,当我通过UI更改它时,它不会反映在控制器中,但它在UI中可用,我看到所选的值。我尝试了$ watch和onChange来看,但他们两个都没有工作。这有什么不对?

2 个答案:

答案 0 :(得分:2)

似乎对我来说很好。以下是使用您提供的代码的示例。

&#13;
&#13;
var app = angular.module('myApp', []);

app.controller('Ctrl', function($scope) {

  $scope.languages = [{
    name: "Java",
    key: "java",
  }, {
    name: "C",
    key: "c",
  }];

  $scope.$watch("selectedLanguage", function(newValue, oldValue) {
    console.log("watch", newValue, oldValue);
  });

  $scope.changeLanguage = function() {
    console.log("language changed: " + $scope.selectedLanguage)
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
  <select class="form-control" ng-change="changeLanguage()" ng-model="selectedLanguage" ng-options='lang.key as lang.name for lang in languages'></select>
  <p>{{selectedLanguage}}</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

很奇怪,也许问题不存在?在pluncker它工作

   (function() {

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

        app.controller('myCtrl', ['$scope',
        function($scope) {
          $scope.languages = [{
            name: "Java",
            key: "java",
          }, {
            name: "C",
            key: "c",
          }];

          $scope.$watch("selectedLanguage", function(newValue, oldValue) {
            console.log("watch", newValue, oldValue);
          });

          $scope.changeLanguage = function() {
            console.log("language changed: " + $scope.selectedLanguage)
          }
        }
      ]);
        })()

plunker