2016-11-29 35 views
1

以下是问题 - 当可用数字为0时,可以为用户分配有限数量的许可证,但不能再指定其他按钮,并且其他按钮将被禁用。许可证可以删除并重新分配。如何在ngRepeat中保留AngularJS组件的总数

用户列表位于ngRepeat循环中,分配/删除许可证功能位于组件中。当我点击分配/移除按钮时,它会自行更新和总计,但其他组件中的按钮不会更新,直到下一次单击。

这里是我到目前为止的全部代码:http://plnkr.co/edit/T4soR8qpSAzY0cANknsE?p=preview

的HTML:

<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> 

控制器和组件:

.controller('RootController', function() { 
    this.qtyMax = 2; 
    this.qtyAvailable = 1; 

    this.users = [ 
    {firstname: 'john', hasLicence: false, reassignable: true}, 
    {firstname: 'jane', hasLicence: false, reassignable: true}, 
    {firstname: 'joey', hasLicence: false, reassignable: true}, 
    {firstname: 'bob', hasLicence: true, reassignable: true}, 
    ]; 

}) 

.component('assign', { 
    template: `<button ng-click="$ctrl.click($ctrl.hasLicence)">{{ $ctrl.text }}</button>`, 
    controller: function() { 
    this.text = ''; 

    // set the button text 
    this.buttonText = function() { 
     if(this.hasLicence) { 
     this.text = 'remove'; 
     } 
     else if(!this.hasLicence && this.reassignable && this.qty>0) { 
     this.text = 'assign'; 
     } 
     else { 
     this.text = '-'; // eg button disabled 
     } 
    } 

    this.buttonText(); 

    // click function 
    this.click = function(licence) { 
     if(licence === true) { 
     this.hasLicence = false; 
     this.qty++ 
     } 
     else if(this.qty>0) { 
     this.hasLicence = true; 
     this.qty-- 
     } 
     this.buttonText(this.hasLicence); 
     console.log(this.qty) 
    } 

    }, 
    bindings: { 
    hasLicence: '<', 
    reassignable: '<', // not relevant for this demo 
    qty: '=', 
    qtyMax: '<' 
    } 

}); 

回答

2

事情是这样的:

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>` 

使用extendend语法:ng-disabled="$ctrl.qty <= 0 && !$ctrl.hasLicence"只禁用按钮来添加许可证的时候,“免费牌”变种是< = 0

更新Plunkr

+0

真棒,谢谢。这正是我试图实现的目标 – EdwardJPayton

0

如果要执行buttonText()功能具体情况,你可以添加上观看qty变量并执行它:

.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: { 
    ... 
    } 

}); 

更新plunker这里:plunkr

+0

非常感谢!我想避免注入$范围(应该把它放在我的问题中) – EdwardJPayton