簡體   English   中英

從外部角度控制器訪問變量

[英]Access an variable from outside angular controller

我正在使用timetable.js以及后端的角度路由器和 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');
     };
});

我現在要做的是在該控制器之外運行timetable.addEvent()函數。

我希望有人理解我正在嘗試做什么並且可以幫助我。

謝謝!

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

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM