我有一个 Angular 服务,它获取作为 promise 解析的当前用户对象。我有一个由对象 userdetails 填充的部分,该对象在方法调用内调用,但不幸的是,在解决 promise 后调用时,该方法调用不会触发。
.controller('AccountCtrl', [
'$scope', 'userService', '$compile', '$http', 'utility', 'cloudService', function ($scope, userService, $compile, $http, utility, cloudService) {
$scope.userdetails = {};
$scope.downloadPageChk = $scope.paymentHistoryPageChk = $scope.manageGroupsPageChk = "hide";
$scope.getUserAttribute = function (param, x) {
return userService.getAttribute(param, x);
};
cloudService.fetchCurrentUser().then(function (newCurrentuser)
{
if (newCurrentuser)
{
$scope.currentUser = newCurrentuser;
$scope.getUserDetails = function()
{
if (userService && userService.isLoggedIn())
{
$scope.userdetails = JSON.parse(JSON.stringify(currentUser));
}
};
if (newCurrentuser == 'member') {
if (newCurrentuser.features.download) $scope.downloadPageChk = "show";
if (newCurrentuser.features.paymenthistory) $scope.paymentHistoryPageChk = "show";
if (newCurrentuser.group.enabled) $scope.manageGroupsPageChk = "show";
}
}
}
])
partial
<div data-ng-controller="AccountCtrl">
<div data-ng-init="getUserDetails()">
<input type="text" class="form-control pull-left" id="FirstName" name="FirstName" data-placeholder-attr="First Name" data-ng-model="userdetails.firstname" required>
<input type="text" class="form-control pull-left" id="LastName" name="LastName" data-placeholder-attr="Last Name" data-ng-model="userdetails.lastname" required>
</div>
</div>
请让我知道我错过了什么。我现在已经敲了 10 个小时了,如果我将用户详细信息移出,如果 cloudservice.fetchuser().then() 它至少会调用该函数,则不确定当我将其放入其中时会发生什么。
类似 plunk 已在此处创建 http://plnkr.co/edit/pLAB4VpLU7uhlSibHzXP?p=preview 谢谢
最佳答案
如果您只想初始化数据 - 您不需要 $scope.getUserDetails
函数和 data-ng-init="getUserDetails()"
.
Angular 将执行服务 fetchCurrentUser
函数,并在加载时填充 $scope.userdetails
。
cloudService.fetchCurrentUser().then(function (newCurrentuser)
{
if (newCurrentuser)
{
$scope.currentUser = newCurrentuser;
if (userService && userService.isLoggedIn())
{
$scope.userdetails = JSON.parse(JSON.stringify($scope.currentUser));
}
if (newCurrentuser == 'member') {
if (newCurrentuser.features.download) $scope.downloadPageChk = "show";
if (newCurrentuser.features.paymenthistory) $scope.paymentHistoryPageChk = "show";
if (newCurrentuser.group.enabled) $scope.manageGroupsPageChk = "show";
}
}
}
}
参见plunker .
编辑:
如果您希望 getUserDetails
函数在初始化后仍可触发,则应将其放在服务方法之外:
$scope.getUserDetails = function(){
if (userService && userService.isLoggedIn()){
$scope.userdetails = JSON.parse(JSON.stringify($scope.currentUser));
}
};
并根据需要触发它(通过 View 中的 ng-click="getUserDetails()"
或 Controller 中的 $scope.getUserDetails()
)。
关于javascript - 服务调用后, Angular 方法未在 Controller 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001159/