问题描述:

I have the folowing code :

<li ng-repeat="item in items">

<a href="#" ng-if="!item.children" ng-click="checkItem(item,checkBoxModel)">

<input class="align"

ng-click="checkItem(item,checkBoxModel)"

type="checkbox" ng-checked="master"

ng-model="checkboxModel"/>

{{ item.title }}

</a>

</li>

in my controller i have checkItem function:

$scope.checkItem = function(item, checkBoxModel) {

if (checkBoxModel == undefined || checkBoxModel == true) {

....

$scope.master=true;

$scope.checkBoxModel = false;*

} else {

....

$scope.master = false;

$scope.checkBoxModel = true;

}

}

The problem is that when I click on a link all of the checkboxes are checked. I just want the checkbox associated to the link to be checked.

网友答案:

Instead of setting a value master on the controllers $scope object, set it on the actual item that you pass in, and set it's ng-checked="item.master" and it's ng-model="item.checkBoxModel"

$scope.checkItem = function(item, checkBoxModel) {
    if (checkBoxModel == undefined || checkBoxModel == true) {
        ....        
        item.master=true;
        item.checkBoxModel = false;
    } else {
        ....
        item.master = false;
        item.checkBoxModel = true;
    }
}
网友答案:

Change your app logic. You have to declare a variable for each item. But as i see, you have one for all in the global $scope named master. The master should have been declared for each item to specify the state of the option box. Then your problem will be solved.

Something like this:

app.js

$scope.items = [
    {
        name: 'example',
        master: false,
        checkboxModel: false
    },
    {
        name: 'example',
        master: false,
        checkboxModel: false
    }
];

$scope.checkItem = function(item, checkBoxModel) {
    if (checkBoxModel == undefined || checkBoxModel == true) {
        ....        
        $scope.items[item].master = true;
        ...
    } else {
        ....
        $scope.items[item].master = false;
        ...
    }
}

index.html

<input class="align"
                   ng-click="checkItem(item, checkBoxModel)"
                   type="checkbox" ng-checked="item.master"
                   ng-model="item.checkboxModel"/>
网友答案:
<li ng-repeat="item in items">
<a href="#" ng-if="!item.children" ng-click="checkItem(item)">
    <input class="align"
           ng-click="checkItem(item)"
           type="checkbox" ng-checked="item.checked"
          />     
             {{ item.title }}                 
 </a>

in my controller i change the value of item.checked

相关阅读:
Top