Qi Zhou
Qi Zhou

Reputation: 41

Why angular JS behave differently?

In Angular JS controller, we put a list into the $scope as below:

$scope.processes = ['process-aa','process-bb', 'process-cc']; 
$scope.selectedProcess=-1;
$scope.collapseProcess = function(index)
{
     console.log('-----------------------in collapseProcess--------------  %s, %s', $scope.selectedProcess, index  );
     return $scope.selectedProcess != index;

 };

 $scope.switchCollapse = function(index) 
 {
     $scope.selectedProcess = index;
 }

the page will list all those processes , there is a div inside of each process, we make this div as toggle. At any time, only one div would be allowed to expand. the HTML as below:

<li ng-repeat="process in processes" class="resultItem" 
   ng-click="switchCollapse($index)"> 
   <div collapse="collapseProcess($index)"  class="collapseBlock"> </div>
</li>

The above code totally works as I expected. When I select the first process, the inner DIV will be expanded, if I then select the second process, the first process's div will be collapsed and the second process's div will be expanded.

However, what I don't understand is why it doesn't work if I change the code to be:

<li ng-repeat="process in processes" class="resultItem" 
   ng-click="selectedProcess=$index"> 
   <div collapse="toggleProcess($index)"  class="collapseBlock"> </div>
</li>

If I change the code as above, then when I click on any process, the DIV won't be expaned. the output in function collapseProcess is: -----------------------in collapseProcess-------------- -1 0 -----------------------in collapseProcess-------------- -1 1 -----------------------in collapseProcess-------------- -1 2

The selectedProcess will always be -1 (which is the initial value in controller). This is very weird, I don't understand why it's like that?

And more interesting, if I change the html to be:

<li ng-repeat="process in processes" class="resultItem" 
   ng-click="selectedProcess=$index"> 
   <div collapse="$scope.selectedProcess != index"  class="collapseBlock">    </div>
</li>

Then, if I select a specific process, its internal div will be expanded, however, the DIV expanded for original selected process won't be collapsed, so, more and more DIVs will will expanded if I select more and more process.

Since I'm a newbie for angular JS, I don't fully understand the difference between my code blocks. Could anyone help on this? Thanks a lot in advance.

Upvotes: 1

Views: 76

Answers (1)

Qi Zhou
Qi Zhou

Reputation: 41

thanks for your response. I missed the $ while typing. The actual code does have $index.

And I figured out the issue, seems ng-repeat create its own scope, this is why it doesn't work.

if I change the code to be:

 $scope.obj={
    selectedProcess: -1
 };

and refer to obj.selectedProcess in HTML. then it would work. So I guess it's caused by the scope created by ng-repeat. right?

Upvotes: 3

Related Questions