【问题标题】:Forcing DOM to render upon changes to $scope model reference to factory model强制 DOM 在 $scope 模型引用更改为工厂模型时呈现
【发布时间】:2013-12-07 14:55:28
【问题描述】:

我正在使用 AngularJS 1.2.0 通过 websocket 创建一个简单的消息传递应用程序。 HTML 在列表上使用 ng-repeat 来生成总输出(我正在输入的消息数组)。我正在使用工厂来托管“私有”数据和方法,并且只公开视图模型和函数来操作控制器中的数据:

<form class="form-search">
    <input type="text" ng-model="model.input" class="input-large"
           placeholder="Enter your message:">
    <button type="submit" class="btn" ng-click="sendMessage()">Send</button>
</form>

<ul>
    <li ng-repeat="message in model.output track by $index" ng-bind="message"></li>
</ul>


application.controller('MessageCtrl', ['$scope', 'MessageService', function($scope, Service) {
    $scope['model'] = Service.view;

    $scope.sendMessage = function() {
        Service.sendMessage();
    };

    $scope.$watchCollection(function() {
        return Service['view'];
    }, function(data) {
        $scope['model'] = data;
    });
}])
.factory('MessageService', function('Restangular') {
    var Service = {
        // other private properties
        view: {
            input: null,
            output: []
        }
    };

    openConnection();

    function openConnection() {
        // retrieves websocket URL over Restangular
        // opens websocket
    }

    function sendMessage() {

        // sends input over socket
        // promises are resolved and unshifted onto Service['view']['output'].
    }

    return {
        view: Service['view'],
        sendMessage: function() {
            sendMessage();    
        }
    }
}); 

除了当 Service['view'] 中的输出数组收到新消息时 DOM 的 ng-repeat 没有更新之外,一切都正常工作。我尝试在此线程中使用 $watchCollection 作为解决方案:AngularJS : The correct way of binding to a service properties,但这也不起作用。我可以让 DOM 重新渲染的唯一方法是通过更改输入文本或触发 CSS 中的悬停状态来强制它重新渲染。

鉴于此设置,触发摘要的最佳方式是什么,以便在使用新消息数据解析承诺并未转移到输出数组时立即呈现 DOM?我想避免使用 $rootScope 和触发事件,因为当其他控制器使用工厂时,这会变得非常不干净。

【问题讨论】:

    标签: javascript angularjs restangular


    【解决方案1】:

    在服务中,我添加了 $rootScope 依赖项并使用了 $rootScope.$apply() 来解析承诺并更新模型。

    $rootScope.$apply(function() {
        Service['view']['output'].unshift(newMessage)
    });
    

    这似乎解决了摘要问题,尽管我不确定副作用是什么。

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 2016-04-30
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多