Erhannis
Erhannis

Reputation: 4452

AngularJS Scope inconsistency

Ok, this is making me tear my hair out. We're integrating with some ATSs, so I send out some queries, and on receiving responses I set some variables in the scope. I set the variables inside of a $scope.$apply(), so they should update properly - and it seemed like they WERE, until recently. After debugging for an hour or two, I created a line that expresses the weirdness of the problem. Consider the following code:

<div ng-show="aR.g" ng-bind="aR.g ? 'g yes' : 'g no'"></div>

Note that if shown, the text should be "g yes", and if hidden, it should be "g no". However, the element was hidden, and upon inspecting it, I found the following:

<div ng-show="aR.g" ng-bind="aR.g ? 'g yes' : 'g no'" class="ng-binding ng-hide">g yes</div>

This means that ng-show evaluated aR.g to false, yet ng-bind evaluated aR.g to true. How is that even possible? Surely that's a bug?

Upvotes: 0

Views: 119

Answers (3)

It is possible ussually to do it without apply. It is also possible to use

ng-if="normalReadableName" without ternary operator.

At first look into console if there isn't any error.

If not, its hard to say without the code but I suppose you are facing problem when directive above creates scope. https://github.com/angular/angular.js/wiki/Understanding-Scopes

Or You are reasigning whole object so watch reffers to the previous assigned. Similar problem described here : Update bootstrap angularjs table with real time data on the fly using ng-repeat

Syntax "controller as" mentioned there could help if it is one of these problems.

Upvotes: 1

Reyraa
Reyraa

Reputation: 4274

I think you have a bug some where else, making this part of code to crush. I've created a pen for you.

controller:

$scope.aR = {
    g: true
  }

View:

div(ng-app="app")
  div(ng-controller="TestController")
    div(ng-if="aR.g" ng-bind="aR.g ? 'g yes' : 'g no'")

Upvotes: 1

Erhannis
Erhannis

Reputation: 4452

Ok, so I still don't know WHY it's like this. But if you replace ng-if="aR.g" with ng-if="aR.g ? true : false", it works as it should. This is horrifying in that I now have no idea what parts of my logic will work as they should - it's not strictly a matter of simplicity of the expression or anything, as the actual part that was failing was, like, Z in ng-if="X && Y != 'blah' && Z". For some reason ng-if="X && Y != 'blah' && (Z ? true : false)" worked as expected.

I may have fixed my problem, but I'd appreciate if anybody knows how this could have happened - I'm now super paranoid about the rest of my code.

Upvotes: 0

Related Questions