我的指令中有以下标记:
<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来看,但他们两个都没有工作。这有什么不对?
答案 0 :(得分:2)
似乎对我来说很好。以下是使用您提供的代码的示例。
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;
答案 1 :(得分:1)
(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)
}
}
]);
})()