angularjs - 如何通过服务请求和指令使用 Angular 作用域

标签 angularjs service angularjs-directive angularjs-scope

我有一个查询服务的 Controller ,如下所示:

app.controller('CandListCtrl', ['$scope', 'Cand',
  function ($scope, Cand) {

    Cand.query(function(data) {
      //data processing can happen here
      $scope.candidates = data;
    });

  }]);

我的服务查询 Google 表格:

var sheetServices = angular.module('candServices', []);

    sheetServices.factory('Cand', ['$rootScope',
      function($rootScope){
        return {
          query: function(callback) {
            Tabletop.init({
              key: '{{my key}}',
              simpleSheet: true,
              parseNumbers: true,
              callback: function(data, tabletop) {
                if(callback && typeof(callback) === "function") {
                  $rootScope.$apply(function() {
                    callback(data);
                  });
                }
              }
            });
          }
        };
      }]);

我的指令:

app.directive('timeline', function () {

  return function (scope, element, attrs) {

      var events = scope.candidates;
      console.log(events); //undefined
 }
})

我在路线部分 View 中使用时间线指令:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'partials/cand-list.html',
        controller: 'CandListCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

cand-list.html:

<div id="timeLine"><div timeline ng-style="myStyle"></div></div>

我的问题是我无法从指令中访问 $scope.candidates,因为它的范围仅限于查询函数。

我当然可以创建一个闭包,从函数中提取变量值。但这似乎不符合 Angular 。

最好的前进方向是什么?

最佳答案

您需要学习如何与黑白指令和 Controller 进行通信 首先,您需要创建一个单独的指令作用域,并允许它使用 '=','@' 等访问 Controller 作用域中的数据。

假设你的html是这样的:

<div>
   <timeline candidates="candidates"></timeline>
</div>

还有你的 JavaScript:

app.directive('timeline', function () {

  return {
    scope:{
      candidates:"="
    },

    link:function (scope, element, attrs) {
     scope.$watch('candidates', function() { 
              var events = scope.candidates; 
              console.log(events); 
         }) 
    }
  }
})

Example 了解有关指令的更多信息 documentation

关于angularjs - 如何通过服务请求和指令使用 Angular 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636427/

相关文章:

javascript - 自定义指令 : How evaluate bindings with dynamic HTML

javascript - Angularjs blueimp fileUpload手动触发提交

javascript - watch 在 angularJs 中的指令链接内不起作用

javascript - 使用 Javascript 对象进行 Angular 服务

javascript - 如何在 Controller 中获取父 Controller 作为 Angular 语法

c# - C# 服务的安全配置

当注入(inject)的服务具有较旧的 Grails 版本时,Grails 服务注入(inject) null

javascript - 从另一个指令静态添加 AngularJS 指令

mvvm - 什么时候应该注册我的 Prism 服务?

jquery - icheck 复选框不适用于 angularjs