在另一个未附加视图的控制器内重用一个函数

时间:2016-11-08 10:57:33

标签: angularjs

我正在尝试重用另一个属于另一个页面的控制器内的函数。它没有附加到当前页面的视图。我按照以下步骤操作:

  1. 使用脚本标记
  2. 包含控制器
  3. 使用$ on和$ emit来调用函数
  4. 不幸的是,什么都没发生。该控制器仍然正常初始化,但它不接收来自$ emit的调用。

    如果有人能帮助我弄清楚,我非常感激。

3 个答案:

答案 0 :(得分:1)

你为什么要那样做? Angularjs具有专门用于此目的的概念服务 - 代码可重用性。您需要做的就是创建一个服务,并将其注入您的控制器中以使用它。见下文。

app.service('hexafy', function() {
   this.myFunc = function (x) {
     return x.toString(16);
   }
});

然后在控制器中,

app.controller('myCtrl1', function($scope, hexafy) {
   $scope.hex = hexafy.myFunc(255);
});

app.controller('myCtrl2', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(1023);
});

请记住,角度服务是单身。

答案 1 :(得分:0)

TL; DR:这很可能是因为您应该使用$broadcast方法而不是$emit

Angular's documentation of $scope中,我们可以找到:

  

$emit(name, args);

     

通过范围层次结构调度事件名称向上,通知已注册的$rootScope.Scope侦听器。

鉴于:

  

$broadcast(name, args);

     

向所有通知已注册的$rootScope.Scope听众的子范围(及其子级)调度事件名称向下

查看下面的综合代码段。您可以使用发射器来查看接收器的通知!

var myApp = angular.module('myApp', []);
myApp.controller('ReceiverCtrl', ['$scope', function ListenerCtrl($scope) {
  this.count = 0;
  $scope.$on('my-event', function(e, data) {
    this.received = '\'my-event\' has been ' + data + '!';
    this.count++;
  }.bind(this));
}]);

myApp.controller('EmitterCtrl', ['$scope', function EmitterCtrl($scope) {
  $scope.clickEmit = function() {
    $scope.$emit('my-event', 'emitted');
  };

  $scope.clickBroadcast = function() {
    $scope.$broadcast('my-event', 'broadcasted');
  };
}]);
div[ng-controller] {
  padding: 16px;
}

div.receiver {
  background-color: steelblue;
}

div.emitter {
  background-color: hotpink;
}

.console {
  font-family: monospace;
  background: #eee;
}

.console::before {
  content: '> ';
}

.highlight {
  color: white;
}

button {
  font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="ReceiverCtrl as outer" class="receiver">
    <div class="console">{{outer.received}}</div>
    received total: <span class="highlight">{{outer.count}}</span>
    <div ng-controller="EmitterCtrl" class="emitter">
      <button ng-click="clickEmit()">$emit()</button>
      <button ng-click="clickBroadcast()">$broadcast()</button>
      <div ng-controller="ReceiverCtrl as inner" class="receiver">
        <div class="console">{{inner.received}}</div>
        received total: <span class="highlight">{{inner.count}}</span>
        <div ng-controller="EmitterCtrl" class="emitter">
          <button ng-click="clickEmit()">$emit()</button>
          <button ng-click="clickBroadcast()">$broadcast()</button>
        </div>
      </div>
    </div>
  </div>
</div>

答案 2 :(得分:0)

我意识到没有办法重复使用控制器作为我的期望。我的解决方案将其附加到一个空的隐形标签中。但是,如果有人能为这种情况找到更好的解决方案,我欢迎。