如何从Controller中查看服务中的变量以打开模态?

时间:2015-11-23 16:34:14

标签: javascript angularjs angularjs-directive angularjs-service

http://plnkr.co/edit/bdHiU0?p=preview

如果我需要的变量是服务返回的一些数据我很好,这样的东西就可以了:

vm.tickersObject = InitTickersFactory.returnTickers();

然而,在上面的plnkr示例中,我只是在我的tickerController中设置了一个切换变量,然后传递并将值存储到AddTickerFactory

点击打开模式按钮查看日志。

现在我需要tickerModalController获取该变量,然后显示或隐藏模态。但vs.showModal tickerModalController中的false仍然停留在vs.showModal = AddTickerFactory.getToggleStatus();

<ticker-modal></ticker-modal> <tickers-panel></tickers-panel>

标记

// Code goes here

angular.module('app', [])

.directive('tickersPanel', function() {
    return {
    restrict: "E",
    link: function($scope, el, attrs) {
      // console.debug($scope, attrs);
    },
    template: '<div class="ticker" ng-controller="tickerController"><button ng-click="openModal()">Open Modal</button></div>'
  };
})

.directive('tickerModal', function() {
    return {
    restrict: "E",
    link: function($scope, el, attrs) {
      // console.debug($scope, attrs);
    },
    template: '<div class="modal" ng-show="showModal" ng-controller="tickerModalController"><h1>Hello World!</h1></div>'
  };
})

.factory('AddTickerFactory', [function() {
    var vm = this;
        vm.addTickerToggle = false;

    var addTicker = {
        toggleAddTicker : toggleAddTicker,
        getToggleStatus : getToggleStatus
    }

    return addTicker;

    function toggleAddTicker(bool) {
      console.log(bool);
      vm.addTickerToggle = bool;
    }

    function getToggleStatus() {
        return vm.addTickerToggle;
    }
}])

.controller('tickerController', 
  ['$scope',
   'AddTickerFactory',
   function($scope,
            AddTickerFactory) {

  var vs = $scope;
      vs.addTicker = false;

  vs.openModal = openModal;

  function openModal() {
        vs.addTicker = !vs.addTicker;
        AddTickerFactory.toggleAddTicker(vs.addTicker);
  }
}])

.controller('tickerModalController', 
  ['$scope',
   'AddTickerFactory',
   function($scope,
            AddTickerFactory) {

  var vs = $scope;
      vs.showModal = false;

  vs.showModal = AddTickerFactory.getToggleStatus();
  console.log('vs.showModal',vs.showModal);

  vs.displayModal = displayModal;

  function displayModal() {
    vs.showModal = !vs.showModal;
  }
}]);

完整代码

vs.showModal = AddTickerFactory.getToggleStatus();
console.log('vs.showModal',vs.showModal);

$scope.$watch('vs.showModal', function(current, original) {
    console.log('current',current);
    console.log('original',original);
});

我尝试添加一块手表,但它没有显示任何变化:

bz2

0 个答案:

没有答案