我目前正在尝试使用来自一个控制器的服务从 Web API 中检索行计数值,然后在从数据库中检索到该值后更新另一个控制器的变量——同时避免使用 $scope 或 $rootScope。
下面是 Controller1 - 当服务中的值更改时,此控制器需要更新其变量。目前它运行正常,但我想避免使用 $scope 或 $rootScope:
(function() {
'use strict';
angular
.module('app.event')
.controller('Controller1', Controller1);
Controller1.$inject = ['service1', '$stateParams', '$rootScope'];
/**
* Controller 1
* @constructor
*/
function Controller1(service1, $stateParams, $rootScope) {
// Declare self and variables
var vm = this;
vm.number = 0;
init();
$rootScope.$on('countChanged', refresh);
/**
* Initializes the controller
*/
function init() {
service1.refreshCount($stateParams.id);
}
/**
* Refreshes the count
* @param {object} event - The event returned from the broadcast
* @param {int} count - The new count to update to
*/
function refresh(event, count) {
vm.number = count;
}
}
})();
服务 - 我想避免在这里使用 $rootScope.$broadcast :
(function() {
'use strict';
angular
.module('app.event')
.factory('service1', service1);
service1.$inject = ['APP_URLS', '$http', '$rootScope'];
/**
* The service
* @constructor
*/
function service1(APP_URLS, $http, $rootScope) {
// Declare
var count = 0;
// Create the service object with functions in it
var service = {
getCount: getCount,
setCount: setCount,
refreshCount: refreshCount
};
return service;
///////////////
// Functions //
///////////////
/**
* Re-calls the web API and updates the count
* @param {Guid} id - The ID needed for the API call parameter
*/
function refreshCount(id) {
$http({ url: APP_URLS.api + '<TheAPINameHere>/' + id, method: 'GET' }).then(function (response) {
setCount(response.data.Count);
changed();
});
}
/**
* Returns the count value
*/
function getCount() {
return count;
}
/**
* Re-calls the web API and updates the count
* @param {int} newCount - The new count value
*/
function setCount(newCount) {
count = newCount;
changed();
}
/**
* Broadcasts a change event to be picked up on in Controller1
*/
function changed() {
$rootScope.$broadcast('countChanged', count);
}
}
})();
下面是 Controller2 中的一个函数,用于更新服务中的值 - 我希望能够在执行此操作后立即更新 Controller1 中的值:
/**
* Removes a row from the database
* @param {object} field - The data row object that we're deleting from the table
*/
function remove(field) {
// Delete the row from the database
service2.delete(field.Id);
// Remove the row from the local data array and refresh the grid
vm.data.splice(vm.data.indexOf(field), 1);
// Set the count in the service to update elsewhere
service1.setCount(vm.data.length);
vm.indices.reload();
}