【问题标题】:Angularjs: ng-model doesn't refresh after object changeAngularjs:对象更改后ng-model不刷新
【发布时间】:2013-06-19 17:14:22
【问题描述】:

我正在使用 angularjs,但我在更新 ng-model 时遇到了一点问题。

我有一个 $scope 对象,它在 ng-controller 之外的服务中加载了 ajax。

服务如下:

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;
});

这可行,我在 ng-controller 中的 $scope 对象已更新。

现在我需要更新并显示 html 页面中输入文本中的值,该值具有我更新对象的 ng-model 属性,如下所示:

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

但是,当我执行 $scope.safeApply() 函数时(我使用 safeApply 来防止“$digest already in progress 错误”),ng-model 没有任何变化。

这是我的 ng 控制器:

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));
        });
    });

我做错了什么?

更新 ng-model 和显示值需要什么?

谢谢

【问题讨论】:

  • 另外关于 safeApply 不确定您使用的是哪个版本的 Angular 但我还没有遇到您所指的错误,使用了 1.0.7 和 1.1.4 您使用的是什么版本?这是一个长期存在的问题吗?
  • 你的代码在这个小提琴中工作:jsfiddle.net/bcaudan/PVmG6,我只用 $timeout 替换 $http 发送虚假响应。
  • 感谢所有回答,这是在外部 div 中声明的 ng-controller 的问题。现在一切正常

标签: javascript angularjs angularjs-scope


【解决方案1】:

看起来这里的大部分内容都是正确的,我假设您已经调试过,发现它命中了这一行:

$scope.invitation = d;

如果是这种情况,我唯一能看到的错误是在顶部附近定义的 HTML 元素没有包含在定义控制器的区域内。

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

【讨论】:

  • 你是对的。我在另一个不包含输入标签的 div 中声明了控制器,并且通过您的回答,我意识到了我的错误。现在一切正常,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多