Angularjs工厂和变量访问

时间:2013-08-29 18:32:27

标签: javascript angularjs

我最近改变了我的工厂 FROM

app.factory('controllerComm', function($rootScope)
{
  var showVforum    = {};
  showVforum.result = false;
  showVforum.prepBroadcast = function(val)
  {
    this.result = val;
    this.broadcastVal();
  }

  showVforum.broadcastVal = function()
  {
    $rootScope.$broadcast('toggleVforum')
  }
  return showVforum;
});

THIS

app.factory('controllerComm', ['$rootScope', function($rootScope)
{
  var showVforum    = {};
  showVforum.result = false;
  showVforum.prepBroadcast = function(val)
  {
    this.result = val;
    this.broadcastVal();
  }

  showVforum.broadcastVal = function()
  {
    $rootScope.$broadcast('toggleVforum')
  }
  return showVforum;
}]);

我这样做是出于JS缩小的原因。在我改变它之前,我在我的一个控制器中工作了这个:

$scope.$on('toggleVforum', function()
{
  $scope.isVisible = controllerComm.result;
  $('#vforum').verticalAlign();
  player.play();
});

controllerComm.result现在正在返回undefined,因为我改变了工厂,我无法弄清楚原因。有什么想法吗?

修改

错误:

TypeError: Object function e(e,f,i){var j=c.defer(),k=j.promise,l=y(i)&&!i,f=a.defer(function(){try{j.resolve(e())}catch(a){j.reject(a),d(a)}l||b.$apply()},f),i=function(){delete g[k.$$timeoutId]};
k.$$timeoutId=f;g[f]=j;k.then(i,i);return k} has no method 'prepBroadcast'
    at Object.$scope.hideVforum (http://localhost/aventos/resources/js/aventos.js:645:20)
    at http://localhost/aventos/resources/js/angular.min.js:72:251
    at http://localhost/aventos/resources/js/angular.min.js:144:140
    at Object.e.$eval (http://localhost/aventos/resources/js/angular.min.js:88:347)
    at Object.e.$apply (http://localhost/aventos/resources/js/angular.min.js:88:454)
    at HTMLButtonElement.<anonymous> (http://localhost/aventos/resources/js/angular.min.js:144:122)
    at HTMLButtonElement.x.event.dispatch (http://localhost/aventos/resources/js/jquery-1.10.2.min.js:5:14129)
    at HTMLButtonElement.v.handle (http://localhost/aventos/resources/js/jquery-1.10.2.min.js:5:10866) 

1 个答案:

答案 0 :(得分:1)

尝试使用广播传递结果变量。

$rootScope.$broadcast('toggleVForum',{result: this.result});

controllerComm未在 $ on 侦听器中定义,即使您可能将其注入到定义侦听器的控制器中。

$scope.$on('toggleVForum',function(evt,args){
    $scope.isVisible = args.result;
    ...
});