javascript - 从 $scope 外部访问集合

标签 javascript angularjs

好的..我已经尝试过 angular.js。太棒了。我印象深刻。我可以得到绑定(bind)和东西..酷。 现在,如果我需要从 $scope 之外访问我的数据怎么办?假设我有一个 signalR 集线器,它发送一些数据和拦截该数据的函数,并且应该添加新项目或修改现有项目。我怎么做?您能否在此示例中向我展示如何从 click 句柄访问 $scope.twitterResult

<script>
    angular.module('Twitter', ['ngResource'])

    function TwitterCtrl($scope, $resource){
        $scope.twitter = $resource('http://search.twitter.com/:action',
        {action: 'search.json', q: 'obama', callback:'JSON_CALLBACK'},
        {get:{method:'JSONP'}});
        $scope.doSearch = function(){
        $scope.twitterResult = $scope.twitter.get();
      }
    }

    $(function(){
      $('#addItem').click(function(){
           // add a row to $scope.twitterResult
      });
   });
</script>

<body>
   <div data-loading></div>
    <div ng-controller='TwitterCtrl' ng-init="doSearch()">
        <ul>
           <li ng-repeat='tweet in twitterResult.results'><p> {{tweet.text}}</p></li>
         </ul>
    </div>
</body>

最佳答案

更好的方法是将“信号中心”包装在 AngularJS 服务中。看看我关于 using web sockets with AngularJS 的博客文章,特别是“与 Socket.IO 交互”。

你为什么这么写:

$(function(){
  $('#addItem').click(function(){
       // add a row to $scope.twitterResult
  });
});

而不只是使用ng-click?这是一些第三方代码或小部件吗?在此之前,我将尽力为您提供更好的建议并编写一些示例代码。

如果您必须注册事件处理程序,您应该通过 directive 来完成此操作。否则,当您开始管理这些 Angular 外事件绑定(bind)的生命周期时,事情会变得复杂。

关于javascript - 从 $scope 外部访问集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279504/

相关文章:

javascript - 两个按钮调用同一个函数,如何知道哪个按钮调用了

javascript - KeystoneJS 错误无法在 openshift 上安装

angularjs - 在 Angular ui Bootstrap 中控制 isOpen

angularjs - Angular 带错误 : [$injector:unpr] Unknown provider: $datepickerProvider

javascript - Angularjs:处理点击禁用的 radio

javascript - $scope :scope mean in angularjs 是什么意思

javascript - InDesign : How to properly use placeXML()

javascript - Reactjs类型错误: Unable to get property 'string' of undefined or null reference Anonymous function

javascript - POST angularjs 后强制页面刷新

javascript - 使用 jQuery Datepicker 的英国夏令时(计算丢失 1 天)