2016-09-19 44 views
1

我將timetable.js與角度路由器和Firebase一起用於後端。我的代碼如下所示:訪問外部角度控制器的變量

這是HTML文件的角度路線:

<div class="timetable" ng-init="initTimetable()"></div> 

這就是我處理從該路由器我所有的功能文件:

myApp.controller('myController', function($scope) { 

    $scope.initTimetable = function() { 
     var timetable = new Timetable(); 
     timetable.setScope(8, 14); 

     timetable.addLocations(['Place 1', 'Place 2', 'Place 3']); 

     timetable.addEvent('Homework', 'Place 1', new Date(2016,9,10,11,45), new Date(2016,9,10,12,30)); 

     var renderer = new Timetable.Renderer(timetable); 
     renderer.draw('.timetable'); 
    }; 
}); 

我」什麼現在m試圖做的是在該控制器外部運行那個timetable.addEvent()函數。

我希望有人明白,我想要做什麼,可以幫助我。

謝謝!

+0

你是從的角度內caling timetable.addEvent()(服務,控制器,指令)? – Nix

+0

我試過的只是從另一個js文件中調用時間表變量,其中原因沒有解決。 –

+0

您可以在指令中使用** timetable.addEvent()**通過傳遞來自dom的值 –

回答

1

如何使用角度來做到這一點的例子。我所做的只是創建一個快速和骯髒的fiddle,將您的代碼放入指令中。在該指令中,我添加了一個addEvent按鈕,現在只是每次都創建相同的事件。你需要更新這個來接收添加一個事件所需的輸入(我今天晚些時候會更新小提示,告訴你如何做到這一點)。

搗鼓出了這一切:http://jsfiddle.net/ncapito/kkxphvg7/

指令定義

angular.module('myApp').directive('timetable', [function() { 
    return { 
     scope: { 
     locations: '=' 
     }, 
     restrict: 'E', 
     replace: true, 
     controller: TimetableController, 
     template: '<div><div class="timetable"></div><button ng-click="addEvent()">Add Event</button></div>', 

    }; 
    }]); 

指令控制器

function TimetableController($scope) { 
    var timetable = new Timetable(); 
    var renderer = new Timetable.Renderer(timetable); 

    init(); 
    $scope.addEvent = addEvent; 

    var idx = 3; 

    function addEvent() { 
     var newLocation = 'Place ' + ++idx; 
     $scope.locations.push(newLocation); 

     //add if new 
     timetable.addLocations([newLocation]); 
     timetable.addEvent(
     'Homework' + idx, newLocation, //need to add a ui to collect this 
     new Date(2016, 9, 10, 11, 45), //need to add a ui to collect this 
     new Date(2016, 9, 10, 12, 30) //need to add a ui to collect this 
    ); 

     render(); 
    } 

    function init() { 
     timetable.setScope(8, 14); 
     timetable.addLocations($scope.locations); 
     timetable.addEvent('Homework', $scope.locations[0], new Date(2016, 9, 10, 11, 45), new Date(2016, 9, 10, 12, 30)); 

     render(); 
    } 

    function render() { 
     renderer.draw('.timetable'); 
    } 

    } 
+0

謝謝你的回答,明天我會看看。 –