2016-09-19 41 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

谢谢你的回答,明天我会看看。 –