angularJS中的数据绑定未更新-UI未显示$scope变量中的更改

angularJS中的数据绑定未更新-UI未显示$scope变量中的更改,angularjs,Angularjs,我在AngularJS中遇到了一个问题,我在自定义服务上使用回调来将数据从一个控制器传递到另一个控制器 特别是,我正在尝试创建一个非常简单的日志记录服务,其中一个控制器向该服务注册一个侦听器函数,以便在记录消息时接收更新,而另一个控制器在单击UI中的按钮时记录消息(触发第一个控制器中的侦听器) 然后,侦听器函数更新$scope.messages变量,以在UI中显示新记录的消息。但是,当新到达的消息到达侦听器函数时,UI不会更新 我相信这是因为AngularJS不知道$scope.messages

我在AngularJS中遇到了一个问题,我在自定义服务上使用回调来将数据从一个控制器传递到另一个控制器

特别是,我正在尝试创建一个非常简单的日志记录服务,其中一个控制器向该服务注册一个侦听器函数,以便在记录消息时接收更新,而另一个控制器在单击UI中的按钮时记录消息(触发第一个控制器中的侦听器)

然后,侦听器函数更新
$scope.messages
变量,以在UI中显示新记录的消息。但是,当新到达的消息到达侦听器函数时,UI不会更新

我相信这是因为AngularJS不知道
$scope.messages
正在更新。 但是,尝试将
$scope.messages
的更新包装为
$scope.$apply
无效
($apply已在进行中)

HTML代码:

<div ng-app="myApp">
    <div ng-controller="ButtonCtrl">
        <button type="button" ng-click="logMessage()">Button</button>
    </div>
    <div id="console" ng-controller="ConsoleCtrl">
         <div ng-repeat="consoleItem in messages">{{consoleItem.message}}</div>
    </div>
</div>
为了方便起见,还可以在JSFIDLE上找到代码:

任何帮助都将不胜感激:-)


谢谢

您的代码正在运行,只是这一行:
$scope.messages.unshift(msgObj.message)
仅当模板希望
$scope.messages
成为对象列表时,才将消息字符串添加到
$scope.messages
。因此将其更改为
$scope.messages.unshift(msgObj)应该可以做到这一点。

好吧,这太尴尬了。。。我想,有时候你只是需要别人来看看这些明显的错误。谢谢
var module = angular.module('myApp', []);

module.factory('MyConsole', function($rootScope) {
    var listeners = [];
    var myConsoleService = {};

    myConsoleService.log = function(messageObj) {
      angular.forEach(listeners, function(listener){
             listener(messageObj);
      });
   };

   myConsoleService.registerListener = function(listener) {
      listeners.push(listener);
   };

  return myConsoleService;
});

function ConsoleCtrl($scope, MyConsole){
    $scope.messages = [{"message":"First message!"}];
    MyConsole.registerListener( function(msgObj){
       // while this console.log call below works as expected, the $scope.messages.unshift call does not update the view
       $scope.messages.unshift(msgObj.message);
       console.log($scope.messages);
    });
}

function ButtonCtrl($scope, MyConsole) {
     $scope.logMessage = function () {
        MyConsole.log({message:"myLogmessage"});
     };
}