Ronnie
Ronnie

Reputation: 11198

Reference an element later in angular

I have two images that you have to select one or the other and the class changes depending on which you select using ng-click. On proceeding to the next step, I make an object and store references to what was just selected:

$scope.cabinetDetails.cabinetType = {
    name: $scope.currentElement.obj.name,
    image: $scope.currentElement.obj.image,
    ref: $scope.currentElement
};

$scope.currentElement is whatever image I had selected and I would think I could later access it via: $scope.cabinetDetails.cabinetType.ref

Let's say I am on step two and I want to make a change to step one. I click my breadcrumb to go back and I see step one again (this works fine). What I'd like to happen is the class changes to its selected state.

On loading step one, I do this:

if ($scope.cabinetDetails.cabinetType != null)
{
    $scope.currentElement = $scope.cabinetDetails.cabinetType.ref;
}

I would imagine this would preselect the image I had before since my ng-repeat does a simple check in the ng-class portion:

<div ng-repeat="obj in currentObject">
    <div class="img-select" ng-click="setActive(this)" ng-class="{itemSelected : isActive(this)}">
      <div align="center">
        <img ng-src="resources/images/aventos/{{obj.image}}" />
      </div>
      <div class="img-title">{{obj.name}}</div>
    </div>
</div>

The isActive() function is also rather simple:

$scope.isActive = function(element)
{
    return $scope.currentElement === element;
}

I've been trying to avoid posting a question but I can't seem to figure this one out. It's like my reference is invalid

Upvotes: 1

Views: 139

Answers (2)

Chandermani
Chandermani

Reputation: 42669

One problem is see in you html template is use of this in multiple methods. this would refer to the current scope object of the ng-repeat.

Assuming you are iterating over a array, can you change this line

<div class="img-select" ng-click="setActive(this)" ng-class="{itemSelected : isActive(this)}">

to

<div class="img-select" ng-click="setActive(obj)" ng-class="{itemSelected : isActive(obj)}">

Also verify that the method setActive and isActive are working on your object instead of scope instance, by debugging the method.

Upvotes: 2

checketts
checketts

Reputation: 14963

The problem is with the this keyword. this is not available to pass through from the template.

Instead of referencing elements, take a step back and reference the underlying item in the repeater. Try changing this to obj (the object in your ng-repeat="obj in currentObject")

ng-click="setActive(obj)" ng-class="{itemSelected : isActive(obj)}

Upvotes: 1

Related Questions