我创建了一个名为SharedService的工厂
angular.module('Fms').factory('SharedService', function()
{
var userdetails=false;
return userdetails;
})
belew控制器共享此工厂
angular.module('Fms').controller('mainCtrl',['$scope','SharedService',function($scope,SharedService)
{
$scope.userdetails=SharedService;
$scope.$watch(SharedService, function(newValue, oldValue, scope)
{
console.log(SharedService)
if (newValue && newValue !== oldValue)
{
$scope.userdetails = SharedService;
}
});
}]);
angular.module("Fms").controller('LoginCtrl',['$scope','$http','$location','SharedService',function($scope,$http,$location,SharedService)
{
$scope.results ="";
$scope.name ="";
$scope.pass ="";
$scope.errormessage="";
$scope.login=function()
{
$http(
{
method: 'get',
url: '/login',
params : {username:$scope.name,password:$scope.pass},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).
success(function(response)
{
if(response=="success")
{
$scope.errormessage="";
SharedService.userdetails=true;
$location.path("/home")
}
else
{
$scope.errormessage="Enter valid Username & Password";
SharedService.userdetails=false;
}
}).
error(function(response)
{
});
}
}]);
问题是我想根据验证响应从LonginCtrl控制器更新SharedService工厂变量userdetails。
同时$ scope.userdetails = SharedService;来自mainCtrls需要使用$ watch进行更新。但它不起作用
答案 0 :(得分:0)
我建议你像这样写你的工厂
angular.module('Fms').factory('SharedService', function() {
var _userdetails = false;
return {
changeUserDetails: function(details) { _userdetails = details },
getUserDetails: function() { return _userdetails }
}
})
在mainCtrl中你应该写
$scope.userdetails=SharedService.getUserDetails();
$scope.$watch(function(){ return SharedService.getUserDetails()}, function(newValue, oldValue)
{
if (newValue && newValue !== oldValue)
{
$scope.userdetails = SharedService.getUserDetails();
}
});
并在loginCtrl
中SharedService.changeUserDetails(true);