Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add $$hashKey to object in Angular

The Angular-specific property on enumerated objects $$hashKeycan be used for a lot of things.

For example DOM-targeting;

<div ng-repeat="obj in objects">
    <label for="field-{{obj.$$hashKey}}">
        Label
    </label>
    <input type="text" id="field-{{obj.$$hashKey}}" />
</div>

In some weird case I am experiencing now the $$hashKey prop is not yet set on a object I want to access it on even though it is being repeated with Angular. Is there a way to set this property yourself when initializing the object?

Edit: My guess is that there is some form of execution order issue, that I access the property when Angular has yet to process the repetition. I am deep watching an object, within that object is an array with objects which is getting repeated. It's also on one of those objects that I need to access the $$hashKey property on.

Simple example;

var MyController = function($scope, Obj)
{
    $scope.obj = {
        list: [obj, obj, obj, obj]
    };

    $scope.$watch("obj", function()
    {
        var lastObj = $scope.obj.list[$scope.obj.list.length - 1];
        console.log(lastObj.$$hashKey); // Undefined?
    }, true);

    $scope.addObj = function()
    {
        $scope.obj.list.push(new Obj());
    };
};

Edit2: jsFiddle http://jsfiddle.net/2sbWp/2/

like image 493
Rasmus Avatar asked May 06 '14 17:05

Rasmus


1 Answers

Use $timeout with no delay value to defer until the $$hashKey property is available:

$timeout(function(){console.log(lastObj.$$hashKey)});

A working fork of your Fiddle

like image 53
Marc Kline Avatar answered Sep 16 '22 14:09

Marc Kline