Yujia Guo Yujia Guo - 2 months ago 19
Javascript Question

Angular JS render variable in scope function to view and make comparison

Hi I have been using this tag to change my css style, if the condition totalAsset and sortedAsset are same

<div class="table-row" ng-repeat="x in myData" ng-click="sort()"
ng-class="{'lightblue': x.totalAsset == sortedAsset}">


totalAsset is my data in like this

$scope.myData = [
{
totalAsset: "23557"
},
{
totalAsset: "4512190",
},
{
totalAsset: "2190",
},
{
totalAsset: "1256790",
}
]


i have create a function that self sort the totalAsset

$scope.sort = function (){
$scope.unsortedAsset = $scope.myData.totalAsset;
$scope.sortedAsset=$scope.unsortedAsset.split("").sort().join("");
}


in the logic only the first and last row will become blue the other two rows remain same.

Answer

In "sort()" you directly access "$scope.myData.totalAsset". This gets resolved as a reference to the last object in "$scope.myData" that has a "totalAsset" member. Instead you wanted to iterate over all objects in "myData". That can be achieved by supplying a parameter to the sort function like in the code below.

$scope.sort = function (totalAsset){
    $scope.unsortedAsset = totalAsset;
    $scope.sortedAsset=$scope.unsortedAsset.split("").sort().join("");
}

Then you also must call the sort function by supplying the parameter value.

<div class="table-row" ng-repeat="x in myData" ng-click="sort(x.totalAsset)" ng-class="{'lightblue': x.totalAsset == sortedAsset}">
Comments