你在正確的軌道上,使用可以使用工廠或服務來共享控制器之間的代碼。請注意,角度服務(和工廠)是單身人士;它們在應用程序啓動時實例化一次,然後在任何時候將其注入控制器時,您都引用相同的實例。考慮下面的代碼:
var myApp = angular.module('myApp',[]);
myApp.service('MyService', function() {
let _someValue = 'Initial Value';
this.setValue = function(value){
_someValue = value;
}
this.getValue = function(){
return _someValue;
}
});
//First Controller Run
myApp.controller('ControllerA', function($scope, MyService) {
MyService.getValue(); //Initial Value
MyService.setValue("BRAND NEW VALUE!!!");
});
//Run after ControllerA
myApp.controller('ControllerB', function($scope, MyService) {
MyService.getValue(); //BRAND NEW VALUE!!!
});
她你會看到MyService保存someValue的狀態。 ControllerA將MyService注入到它並可以使用該服務的方法來設置新值。現在,對於相同狀態的任何後續調用,例如ControllerB,將返回更新後的值。
檢查此SO文檔http://stackoverflow.com/documentation/angularjs/1923/sharing-data/26454/sharing-data-from-one-controller-to-another-using-service#t=201704260743521596768 –