2012-12-30 51 views
0

的編譯部分內服務JM的SO張貼Convert Angular HTTP.get function to a service是迄今爲止我見過的最好的總結和解釋了很多。但是......雖然我的服務在控制器內部工作,但我無法在指令中訪問它。無法訪問指令

"Just inject it"可能是答案,但仍呼籲我的指令中失敗,因爲該服務是「未定義」

我正在寫一個窗口管理器服務。 '...這裏的東西...'是一個指令。

的WindowInfoService跟蹤有關每個窗口信息(姓名&位置現在)。拖動窗口時,指令應該通知WindowInfoService新的位置。

訪問WindowInfoService從控制器的工作原理,但不是指令....任何人都知道如何解決這個問題?我完全陷入困境。

應用程序定義

var RR = angular.module('roadrunner', 
['login', 'launcher', 'ui.directives', 'authentication', 
'current-user', 'windows', 'windowinfo']); 

這裏的指令

/* *** WINDOW MANAGER *** */ 

angular.module('windows', ['windowinfo']) 
.directive('rrwin', ['WindowInfoService', function($compile, WindowInfoService) 
{ 
    console.log('in directive'); 
    var template = "<div class='win win-base' ui-jq='draggable' " 
        + "ui-options='{handle: " + '".win-titlebar"' + "}'>" 
        + " <div class='win-titlebar ui-dialog-titlebar ui-widget-header'>" 
        + "  <span class='win-title'>{{wa.name}}</span>" 
        + "  <div role='button' class='win-close'>" 
        + "   <span class='win-close-icon'>&nbsp;&nbsp;</span>" 
        + "  </div>" 
        + " </div>" 
        + " <div class='win-content' ng-transclude>" 
        + " </div>" 
        + "</div>"; 

    var directive = 
    { 
     restrict: 'E', 
     scope: { wa: '=winAttrs' }, // localName: html-attr-name 
     transclude: true, 
     compile: function (tElement, tAttr, transclude) 
     { 
      tElement.html(template); 
      return function (scope, element, attr) 
      { 
       console.log('inner fcn'); 
       var inner = $(element).children(); 
       $(inner).css('top', scope.wa.top); 
       $(inner).css('left', scope.wa.left); 
       $(inner).css('width', scope.wa.width); 
       $(inner).css('height', scope.wa.height); 

       element.on("dragstop", function (event) 
       { 
        console.log('stop'); 
        console.log(event.pageX, event.pageY); 
        var winElem = $(event.srcElement).parent(); 
        var h = parseInt($(winElem).css('height')); 
        var w = parseInt($(winElem).css('width')); 
        var t = parseInt($(winElem).css('top')); 
        var l = parseInt($(winElem).css('left')); 

        // this doesn't work! 
        console.log(WindowInfoService.getAllInfo()); 
        WindowInfoService.setInfo({ w: w, h: h, t: t, l: l }) 
       }); 
      } 
     } 
    } 
    return directive; 
}]) 
.controller(
    "windowMgrController", 
    function ($scope, $location, WindowInfoService) 
    { 
     console.log('windowMgrController'); 
     $scope.windowList = WindowInfoService.getAllInfo(); // this works! 
    } 
); 

回答

2

你忘注入$編譯:

angular.module('windows', ['windowinfo']) 
.directive('rrwin', ['$compile', 'WindowInfoService', function($compile, WindowInfoService) 
{ 
    ... 
+0

謝謝!這並不明顯 - 需要很長時間才能找到。 -DW – Danny

+0

如果您將數組用作值,則需要首先將所有服務作爲字符串包括在內(包括角度自己的服務)。 – asgoth