【问题标题】:How do i array.push from inside PubNub function to Angular scope?我如何从 PubNub 函数内部将 array.push 到 Angular 范围?
【发布时间】:2014-05-07 00:14:38
【问题描述】:

我的 HTML

ng-appng-controller 在前面的标记中指定

<div class="statusEntry" ng-repeat="statusInput in statusInputs">
 <span class="userName"> a </span>                
 <span  class="statusMsg"> b </span>                
</div>

控制器

app.controller('globalCtrl', ['$scope', function($scope) {
//someWork
pubnub.subscribe({
channel: "statuses",
callback:
function (data) {

    splitData = data.split(';');
    prepData = '{'+splitData[0]+','+splitData[1]+'}';
    statusInputs.push(prepData);
}
});

当我推送数据时,不会出现新对象。 即使我在statusInputs 前面加上$scope,Angular 也无法获取数据。

看起来我需要将数据从嵌套函数传递到根范围,我不知道如何。

【问题讨论】:

  • 试试 angular.extend($scope,MYService)

标签: javascript angularjs nested pubnub nested-function


【解决方案1】:

当你第一次到达你的控制器时初始化数组:

$scope.statusInputs = [];

在你的回调函数中改变:

statusInputs.push(prepData);

$scope.statusInputs.push(prepData);
//also, because pubnub is defined outside of angular
//call $scope.$apply() to force angular to recognize 
//the change on the scope
$scope.$apply()

基本上,您是在您的范围内声明一个数组,您的 UI 将使用该数组,然后在每次回调时将项目附加到该绑定数组中。

【讨论】:

  • 谢谢,这确实可以正确推送数据。您是否有机会知道为什么新对象不会立即出现,而是在我在input 中输入一个字母之后?我需要以某种方式刷新吗?
  • 我认为 pubnub 与 angular 无关,因此这种更改不会触发摘要循环。在 push 调用之后,添加对 $scope.$apply() 的调用
猜你喜欢
  • 1970-01-01
  • 2012-10-14
  • 2021-05-04
  • 2020-10-17
  • 2020-09-25
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多