简体   繁体   中英

Angular controller not able to read update from service. Any advice?

I have a situation where within my angular service, I have a number of properties. These properties are linked to the controller.

Service:

angular.module('...')
    .factory('PollServ', function PollServ($http, ...) {

        var service = {
            question: '',
            votes: [[]]
        }

        ...

        // make http request to API
        var request = $http({ ...

        // once the value is retrieved, update properties
        request.then(function (res) {

            service.question = res.data.question;
            ...
    }

Controller:

angular.module('...')
    .controller('PollCtrl', function PollCtrl(..., PollServ) {
        $scope.question = PollServ.question;
        $scope.votes = PollServ.votes;
        ...

Now, although the votes are being updated properly, the question is not. I am not doing anything different, except the fact that votes is an array and question is just a regular string. I think the array may have something to do with being able to dynamically update, but not the simple string.

How can I get it to work, without unnecessary turning the string into an array as well?

You said it yourself - the question is a string and thus will not be updated in your controller/view.

What you could do is turning the question into an object. For example:

In Factory

var service = {
    question: {
        name: ''
    },
    votes: [[]]
}

...

service.question.name = res.data.question;

You then need to change the reference in your view to question.name .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM