2016-11-29 36 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