Проблемы с обновлением значения в AngularJS - PullRequest
0 голосов
/ 24 апреля 2018

Я не могу обновить значения в представлении страницы, используя 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, значение не изменяется на странице.Однако во время отладки я вижу изменение значения в области $.

Ответы [ 2 ]

0 голосов
/ 24 апреля 2018

Я попытался повторить проблему, и, похоже, она работает в Fiddle - 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;
    }
}

Комментарии встроены.Надеюсь, это поможет!

0 голосов
/ 24 апреля 2018

Вместо переназначения $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 прототип / прототип наследования в AngularJS .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...