Javascript 如何在ngRepeat中保持AngularJS组件之间的总计
问题是-可以为用户分配有限数量的许可证,当可用数量为0时,不能再分配更多许可证,其他按钮将被禁用。许可证可以删除和重新分配 用户列表位于ngRepeat循环中,分配/删除许可证功能位于组件中。当我单击“分配/删除”按钮时,它会更新自身和总数,但其他组件中的按钮在下次单击之前不会更新 以下是我目前掌握的全部代码: HTML:Javascript 如何在ngRepeat中保持AngularJS组件之间的总计,javascript,angularjs,angularjs-components,Javascript,Angularjs,Angularjs Components,问题是-可以为用户分配有限数量的许可证,当可用数量为0时,不能再分配更多许可证,其他按钮将被禁用。许可证可以删除和重新分配 用户列表位于ngRepeat循环中,分配/删除许可证功能位于组件中。当我单击“分配/删除”按钮时,它会更新自身和总数,但其他组件中的按钮在下次单击之前不会更新 以下是我目前掌握的全部代码: HTML: <body ng-controller="RootController as root"> <pre>qty: {{ root.qtyAvai
<body ng-controller="RootController as root">
<pre>qty: {{ root.qtyAvailable }} / {{ root.qtyMax }}</pre>
<div ng-repeat="user in root.users | orderBy: 'firstname' ">
{{ user.firstname }}
<assign
has-licence="user.hasLicence"
reassignable="user.reassignable"
qty="root.qtyAvailable"
qty-max="root.qtyMax"
></assign>
</div>
</body>
数量:{{root.qtyAvailable}/{{root.qtyMax}}
{{user.firstname}
控制器和组件:
template: `<button ng-disabled="$ctrl.qty <= 0 && !$ctrl.hasLicence" ng-click="$ctrl.click($ctrl.hasLicence)">{{ $ctrl.text }}</button><span ng-if="$ctrl.qty <= 0 && !$ctrl.hasLicence">No licenses are free</span>`
.controller('RootController',function(){
这个qtyMax=2;
此.qtyAvailable=1;
此文件的用户数=[
{firstname:'john',hasplicense:false,可重新分配:true},
{firstname:'jane',hasLicence:false,可重新分配:true},
{名字:'joey',HasLicense:false,reassignable:true},
{名字:'bob',hasLicense:true,可重新分配:true},
];
})
.component('assign'{
模板:`{$ctrl.text}}}`,
控制器:函数(){
this.text='';
//设置按钮文本
this.buttonText=函数(){
如果(本许可证){
this.text='remove';
}
如果(!this.hasLicence&&this.reassignable&&this.qty>0),则为else{
this.text='assign';
}
否则{
this.text='-';//禁用了eg按钮
}
}
这个.buttonText();
//点击功能
this.click=功能(许可证){
如果(许可证===真){
this.hasLicence=false;
这个数量++
}
否则如果(此数量>0){
this.hasLicence=true;
这个数量--
}
this.buttonText(this.hasLicense);
控制台日志(此数量)
}
},
绑定:{
HasLicense:“类似这样的内容:
.component('assign', {
template: `<button ng-click="$ctrl.click($ctrl.hasLicence)">{{ $ctrl.text }}</button>`,
controller: function($scope) { // $scope injection here
...
// Note: you can use arrow functions to omit the assignment of context
var me = this;
$scope.$watch(function() {
return me.qty;
}, function() {
me.buttonText();
});
},
bindings: {
...
}
});
模板:`{{$ctrl.text}没有免费的许可证`
使用extendend语法:ng disabled=“$ctrl.qty如果要执行buttonext()
函数,具体来说,您可以在qty
变量上添加一个手表并执行它:
.component('assign'{
模板:`{$ctrl.text}}}`,
控制器:函数($scope){/$scope注入
...
//注意:可以使用箭头函数忽略上下文的赋值
var me=这个;
$scope.$watch(函数(){
返回我的数量;
},函数(){
me.buttonext();
});
},
绑定:{
...
}
});
更新的plunker here:太棒了,谢谢。这正是我非常想实现的目标!我想避免注入$scope(应该在我的问题中提出)
.component('assign', {
template: `<button ng-click="$ctrl.click($ctrl.hasLicence)">{{ $ctrl.text }}</button>`,
controller: function($scope) { // $scope injection here
...
// Note: you can use arrow functions to omit the assignment of context
var me = this;
$scope.$watch(function() {
return me.qty;
}, function() {
me.buttonText();
});
},
bindings: {
...
}
});