javascript - 强制 DOM 在更改对工厂模型的 $scope 模型引用时进行渲染

标签 javascript angularjs restangular

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

<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 中的悬停状态来强制其重新渲染。

考虑到这种设置,触发摘要的最佳方法是什么,以便一旦用新消息数据解决了 Promise 并不转移到输出数组上,DOM 就会呈现?我想避免使用 $rootScope 和触发事件,因为当其他 Controller 使用工厂时,这会变得非常不干净。

最佳答案

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

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

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

关于javascript - 强制 DOM 在更改对工厂模型的 $scope 模型引用时进行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20149749/

相关文章:

JavaScript OOP 错误的 _this 值

javascript - 如何仅在使用 Angular 2 激活 HTML 元素时启用验证?

在 apache 上使用 UI 路由器的 AngularJS HTML5 模式

javascript - 如何处理带有点 (.) 字符的 angularJS UI 路由器

javascript - 在 GET 之前重新发送 OPTIONS 方法

javascript - 允许跨域通信时使用Javascript获取远程文件的内容

javascript - OpenLayers 添加标记和弹出窗口

javascript - 使用异步 Javascript 调用接收数据

angularjs - 作为一个团体和单独的 Angular 等待多个 promise ?

angularjs - 防止 IE 缓存 AngularJS/Restangular