我有一种情况,我想从控制(配置内)传递数据到外部控制器。我已经尝试过工厂传递数据,但是数据改变后,它仍然保持0(不确定我在哪里做错了)是否有一种方法可以将数据传递给navCtrl在DynamicController更改后?谢谢你的帮助
var app = angular.module('fccrm', ['ngRoute']);
app.factory('idService', function(){
var id = 0;
var itemsService = {};
itemsService.set = function(val) {
id = val;
};
itemsService.get = function() {
return id;
};
return itemsService;
})
app.controller('navCtrl', ['$scope', 'idService', function($scope, idService){
$scope.disable = 'disabled';
console.log(idService.get());
}])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:page/:id', {
template: '',
controller: DynamicController
});
}])
function DynamicController($scope, $routeParams, $http, idService)
{
var templateUrl = '/index.php?controller=lead&action=' + $routeParams.page + '&id=' + $routeParams.id;
idService.set($routeParams.id);
$http.post(templateUrl).success(function(data){
$('#content').html(data);
})
}
如果您希望值保持同步-无论加载顺序如何,那么您应该使用$scope。这就是它的设计目的。
根据你想对这个值做什么,你有很多选择。
显示视图中的值
$scope.displayId = idService.get()
或者更好,为什么不直接添加$rootScope
的id并从那里访问它?
你想要在navCtrl的值改变时得到通知,这样你就可以做进一步的处理
您可以在DynamicCtrl中使用$rootScope.$broadcast('routeParamIdChanged', id)
,然后使用$scope.$on('routeParamIdChanged, fn(ev, id){})
侦听更改,或者您可以创建一个$watch
来检查服务