从外部角度控制器访问变量

时间:2016-09-19 17:15:18

标签: javascript angularjs angular-controller

我使用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');
     };
});

我现在要做的是在该控制器外运行 timetable.addEvent()功能。

我希望有人明白,我想做的事情可以帮助我。

谢谢!

1 个答案:

答案 0 :(得分:1)

如何使用angular来执行此操作的示例。我所做的只是创建一个快速而肮脏的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');
    }

  }