我无法使用angularJS更新页面视图中的值。在调用从网站完成的方法后,这些值应该会发生变化。
保存该值的html元素是
<p>Current song playing: {{currentSong.SongName}}</p>
这是我的角度代码,只有与我的问题相关的部分
var myApp = angular.module('myApp', ['ngMaterial', 'ngMessages']);
myApp.controller('myCtrl', function ($scope, $http, $timeout, $q) {
$scope.currentSong = {
SongName: ''
}
loadCurrent().then(function (data) {
$scope.currentSong = { SongName: data };
});
$scope.updateSong = function () {
loadCurrent().then(function (data) {
$timeout(function () {
$scope.currentSong = { SongName: data };
},200);
});
}
function loadCurrent() {
var deffered = $q.defer();
$timeout(function () {
$http({
method: 'GET',
port: '8080',
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
deffered.resolve(response.data.SongName);
}, function errorCallback(response) {
console.log(response)
});
}, 500);
return deffered.promise;
};
});
初始加载电流设置页面上的值,但是如果我调用updateSong,则页面上的值不会更改。但是,我确实在调试期间看到$ scope内的值发生了变化。
答案 0 :(得分:0)
不是重新分配$scope.currentSong
,而是需要修改它:
loadCurrent().then(function(data) {
$scope.currentSong.SongName = data;
});
$scope.updateSong = function() {
loadCurrent().then(function(data) {
$timeout(function() {
$scope.currentSong.SongName = data;
}, 200);
});
}
请参阅scope prototypal / prototypical inheritance in AngularJS 上的相关帖子。
答案 1 :(得分:0)
我试图复制这个问题,似乎在小提琴中工作 - https://jsfiddle.net/Aks1357/e6yh2n1o/
HTML:
<div ng-controller="MyCtrl">
<p>Current song playing: {{currentSong.SongName}}</p>
<p><input type="button" value="Update Song" ng-click="updateSong()" /></p>
</div>
JS:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', MyCtrl);
function MyCtrl($scope, $timeout, $q, $http) {
$scope.currentSong = {
SongName: ''
}
// Aks: Commented - as it works on load
//loadCurrent().then(function (data) {
//$scope.currentSong.SongName = data;
//});
$scope.updateSong = function () {
loadCurrent().then(function (data) {
// Aks: just directly assign new value
$scope.currentSong.SongName = data;
// Aks: NOTE - the delay parameter for `$timeout` is missing, the intention is to wait until the end of the `$digest` cycle and then set $scope
// Aks: Commented - use below three lines if the value is not updated
//$timeout(function () {
//$scope.$apply();
//});
});
}
function loadCurrent() {
var deffered = $q.defer();
$timeout(function () {
// Aks: Commented - to mimick in fiddle
//$http({
//method: 'GET',
//port: '8080',
//headers: {
//'Content-Type': 'application/json'
//}
//}).then(function successCallback(response) {
deffered.resolve('Dummy Song!');
//}, function errorCallback(response) {
//console.log(response)
//});
}, 500);
return deffered.promise;
}
}
评论内联。希望这有帮助!