简体   繁体   中英

AngularJS changing an element in ng-repeat without chaning them all

I am trying create a simple single page app to keep track of peoples movements. I have it mostly working as I'd like, however when I use my click function in the second, third and forth children of person to change the class of the first child of person it changes the class but also changes the class of all following person div s created by the repeat. What I am trying to do is to isolate each person div so when I change the class of the first child it doesn't echo through all the other person div s. I am unsure on how to do this

here is a sample of the HTML.

<div ng-repeat="x in pers" class="person">
    <div ng-class="name">{{ x.person }}</div>
    <div class="out" ng-click="changeClassOut()">Out</div>
    <div class="in" ng-click="changeClassIn()">In</div>
    <div class="onsite" ng-click="changeClassOnsi()">On site</div>
    <div class="notes">
        <div class='n'></div>
        <div class='dn'>Delete note</div>
        <div class='an'>Add note</div>
    </div>
</div>

and here is a sample of the controller.

app.controller("MainController", ['$scope',  function($scope) {
$scope.pers = [
    {
        person: 'Nick',


    },
    {
        person: "Greg",

    }
];

$scope.name = "name";
$scope.changeClassIn = function(){
    if ($scope.name === "name")
        $scope.name = "name-in";
    else if ($scope.name === "name-out")
        $scope.name = "name-in";
    else if ($scope.name === "name-onsite")
        $scope.name = "name-in"
    else
        $scope.name = "name-in";
};

Any help in this would be greatly appreciated.

You need to move your scope variable name inside each person object for this. Otherwise it stays common for each person . That's the reason it updates classes for each div

$scope.pers = [
{
    person: 'Nick',
    name: 'name
},
{
    person: "Greg",
    name: 'name
}];

Now you have to pass person object through ng-click ng-click="changeClassOut(x)"

<div ng-repeat="x in pers" class="person">
 <div ng-class="name">{{ x.person }}</div>
 <div class="out" ng-click="changeClassOut(x)">Out</div>
 <div class="in" ng-click="changeClassIn(x)">In</div>
 <div class="onsite" ng-click="changeClassOnsi(x)">On site</div>
.......

In your controller,

$scope.changeClassIn = function(person){
    if (person.name === "name")
        person.name = "name-in";
    else if (person.name === "name-out")
        person.name = "name-in";
    else if (person.name === "name-onsite")
        person.name = "name-in"
    else
        person.name = "name-in";
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM