我希望在我的$ http.selectedSong(模型值)发生变化时执行一个方法,但是我似乎无法让它工作,这是怎么回事? :
app.controller('songController', ['$http', function($http) {
$songs = this;
$songs.tracks = [];
$http({
url: "http://api.q-music.be/1.2/tracks/plays?limit=20",
dataType: "jsonp",
jsonp: "callback"
})
.success(function(lastSongsList) {
$http.$watch('selectedSong', function (newVal, oldVal) {
if (newVal !== oldVal) {
alert('hej');
}
});
});
}]);
我的目标是使用从此HTML代码中获得的数据:
<select ng-model="selectedSong" ng-init="selectedSong === songs.tracks[0].title" ng-options="song as song.title for song in songs.tracks"></select>
我想看看我在'select'中选择的值何时发生变化,以便我可以使用此值来执行方法等...
答案 0 :(得分:1)
我假设您使用controller as
语法,在这种情况下,您不是直接在控制器中使用$scope
。但是,您可以设置ng-change
指令,以便在绑定模型发生更改时执行任意代码。
<select ng-model="ctrl.selectedSong" ng-change="ctrl.doStuff()">
这最终比使用$watch
以下是基于上述示例的工作代码
(function() {
'use strict';
function InputController() {
var vm = this;
vm.songs = ['Uptown Funk!', 'Thinking Out Loud','Take Me To Church','Blank Space'];
vm.selectedSong = vm.songs[0];
vm.onSongChange = function() {
alert(vm.selectedSong);
};
}
angular.module('inputs', [])
.controller('InputCtrl', InputController);
}());
&#13;
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<div class="container" ng-app="inputs" ng-controller="InputCtrl as ctrl">
<div class="row">
<div class="col-xs-6">
<h3>Primary</h3>
<select class="form-control" ng-model="ctrl.selectedSong" ng-options="song for song in ctrl.songs" ng-change="ctrl.onSongChange()"></select>
</div>
</div>
</div>
&#13;
答案 1 :(得分:0)