Angularjs: ng-model doesn't refresh after object change

房东的猫 提交于 2019-12-13 18:41:29

问题


I'm working with angularjs and I have a little problem with ng-model update.

I have a $scope object that is loaded with ajax outside of the ng-controller, in a service.

The service is the following:

app.factory('myService', function($http) {
    var myService = {
            async: function(code) {
                var promise = $http.get(url).then(function (response) {
                    return response.data;
                });
                return promise;
            }
    };
    return myService;
});

This works, and my $scope object in ng-controller is updated.

Now i need to update and show the value in an input text in html page, that have the ng-model attribute of my updated object, like this:

<input type="text" name="totalInvitations"
                                ng-model="invitation.totalInvitations" required smart-float/>

But, when I perform $scope.safeApply() function (I use safeApply to prevent "$digest already in progress error") nothing change in ng-model.

Here is my ng-controller:

function editInvitationCtrl(myService, $scope, $http) {
    $scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
                fn();
                console.log(phase);
            }
        } else {
            console.log("apply");
            this.$apply(fn);
        }
    };

    myService.async($scope.code).then(function(d) {
        $scope.invitation = d;
        $scope.safeApply(function(){
            console.log(JSON.stringify($scope.invitation));
        });
    });

What I'm doing wrong?

What I need to update ng-model and show values?

Thanks


回答1:


It looks like most everything here is right, and I assume you debugged to see that it hit this line:

$scope.invitation = d;

If that's the case the only thing I could see being wrong is that the HTML element defined near the top isn't wrapped within the area the controller is defined.

<div ng-controller="editInvitationCtrl>
    <input type="text" name="totalInvitations"
     ng-model="invitation.totalInvitations" required smart-float/>
</div>


来源:https://stackoverflow.com/questions/17197349/angularjs-ng-model-doesnt-refresh-after-object-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!