我正在尝试重用另一个属于另一个页面的控制器内的函数。它没有附加到当前页面的视图。我按照以下步骤操作:
不幸的是,什么都没发生。该控制器仍然正常初始化,但它不接收来自$ emit的调用。
如果有人能帮助我弄清楚,我非常感激。
答案 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)
我意识到没有办法重复使用控制器作为我的期望。我的解决方案将其附加到一个空的隐形标签中。但是,如果有人能为这种情况找到更好的解决方案,我欢迎。