javascript - 从外部 Angular Controller 访问变量

标签 javascript angularjs angular-controller

我正在使用timetable.js以及用于后端的 Angular 路由器和 firebase。我的代码如下所示:

这是 Angular 路由到的 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');
     };
});

我现在想做的是在 Controller 外部运行 timetable.addEvent() 函数。

我希望有人理解我正在尝试做的事情并可以帮助我。

谢谢!

最佳答案

如何使用 Angular 来执行此操作的示例。我所做的就是创建一个快速而肮脏的fiddle,将您的代码放入指令中。在指令中,我添加了一个 addEvent 按钮,现在每次都只创建相同的事件。您需要更新它以获取添加事件所需的输入(我将在今天晚些时候更新 fiddle 以向您展示如何执行此操作)。

fiddle 显示所有这些: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>',

    };
  }]);

指令 Controller :

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

  }

关于javascript - 从外部 Angular Controller 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578628/

相关文章:

javascript - Angular 将字符添加到数组中

javascript - 在模糊/焦点事件上使用 $validators

angularjs - AngularError - app.controller(...) 不是一个函数

javascript - 从 api 返回 true false 的 Angular 过滤器?

javascript - 使用 Javascript 和 PHP 将数据表单传输到 mysql

javascript - 如何使用 CryptoJs 转换为字符串并再次转换回来

javascript - 使用 mongodb/mongoose 有条件地将 5-20k 文档的输入批处理处理为包含多达一百万个文档的集合的有效方法是什么?

angularjs - 如何避免 `modal-backdrop hide` 插入 ionic 缓存?

javascript - 如何在新窗口中打开部分 View 并调用打印方法?

javascript - Bootstrap 后如何激活新的 Angular Controller