Angularjs: ng-model doesn't refresh after obje

2019-07-29 17:22发布

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条回答
萌系小妹纸
2楼-- · 2019-07-29 18:02

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>
查看更多
登录 后发表回答