我的目标是在后台计算余额时显示页面并显示余额。我以为我会尝试将余额分离成自己的指令。所以,我创建了以下指令:
app.directive('smBalanceInfo', function () {
return {
restrict: 'A',
//transclude: true,
//replace: true,
scope: {
title: '@',
calculateBalance: '&',
},
controller: ['$scope', function ($scope) {
$scope.balance = 0;
$scope.calculated = false;
var getBalance = function () {
$scope.balance = $scope.calculateBalance();
$scope.calculated = true;
};
getBalance();
}],
这个非常简单的html:
{{title}}: <span ng-hide="calculated">Calculating...</span>
<span ng-show="calculated" ng-class="{'negative-amount': balance < 0}">{{balance| currency:""}}</span>
在我的表格中,我提出以下内容:
<div class="col-md-4" data-sm:balance-info title="@Labels.totalDueForAllInvoices" calculate-balance="getAccountBalance()"></div>
表单的控制器方法getAccountBalance如下:
$scope.getAccountBalance = function () {
var totalBalance = 0;
if (!$scope.isNew) {
accountsService.getAccountBalance($scope.invoicesObject.accountNameHash).then(function (data) {
totalBalance = data.balance;
return totalBalance;
});
}
else { return totalBalance; }
};
所以,这一切都很好,除了我的指令变量余额未定义且没有任何内容显示,即使我跟踪它时我看到了totalBalance值的计算。
我应该更改以上内容以便能够将控制器函数的值返回到指令中并更全面地获取我想要的行为(例如,在计算余额的同时显示表单)?
答案 0 :(得分:1)
您的指令具有独立的范围,并且从其外部看不到余额变量。尝试将余额添加为指令的范围变量
app.directive('smBalanceInfo', function () {
return {
restrict: 'A',
//transclude: true,
//replace: true,
scope: {
title: '@',
balance:'=',
calculateBalance: '&',
},
controller: ['$scope', function ($scope) {
$scope.balance = 0;
$scope.calculated = false;
var getBalance = function () {
$scope.balance = $scope.calculateBalance();
$scope.calculated = true;
};
getBalance();
}],
然后在你的html模板中将指令平衡变量链接到控制器范围平衡添加属性balance="balance"
,如:
<div class="col-md-4" data-sm:balance-info title="@Labels.totalDueForAllInvoices" balance="balance" calculate-balance="getAccountBalance()"></div>
答案 1 :(得分:0)
在此期间我也解决了这个问题。我的指示非常简单:
(function () {
'use strict';
var app = angular.module('sysMgrApp');
app.directive('smBalanceInfo', function () {
return {
restrict: 'A',
//transclude: true,
//replace: true,
scope: {
title: '@',
calculated: '=',
balance: '=',
},
templateUrl: 'app/templates/smBalanceInfo'
};
});
})();
在主控制器中,我在帐户加载方法的末尾添加了:
$rootScope.$broadcast('sm:focus');
$rootScope.$broadcast('accounts:accountLoaded');
});
};
var getAccountBalance = function () {
var totalBalance = 0;
if (!$scope.isNew) {
accountsService.getAccountBalance($scope.currentAccount.acctNameHash).then(function (data) {
$scope.currentAccount.totalBalance = data.balance;
$scope.balanceCalculated = true;
return totalBalance;
});
}
else {
$scope.balanceCalculated = true;
return totalBalance;
}
};
$scope.$on('accounts:accountLoaded', function (event) {
getAccountBalance();
});
所以,现在我的帐户信息已加载,我看到“正在计算”消息,然后余额就可以了。