The data for the angular app is received in an array and then used with $compile to create an angular directive. For example...
for(i = 0; i < trueTest.length; i++) {
var test = trueTest[i];
$scope.directiveData = {
blockId: test.blockId,
dataType: test.dataType,
type: test.type,
directiveType: test.directiveType
};
$compile("<my-directive block-id='{[{ directiveData.blockId }]}' block-data-type='{[{ directiveData.dataType }]}' block-type='{[{ directiveData.type }]}' block-directive-type='{[{ directiveData.directiveType }]}'></my-directive>")($scope.$new());
elem.find('.SomeElement').append(el);
}
The custom directive my-directive
has an isolated scope with values such as blockId
, blockDataType
, etc...
The key value here is blockId
within my-directive
. It determines the type of data that will be displayed in that specific directive. The issue arises when it appears that $compile
creates elements after the loop has finished, resulting in each directive created by $compile
having the last value from the loop.
It's speculated that $compile generates elements (directives) asynchronously, causing the directives to be created only after the loop ends, with the current values of $scope.directiveData
. Alternatively, the directives may be created as plain DOM elements first, with scopes being assigned afterwards, leading all directives to have the last value of the directiveData
object.
Can someone provide insight into what exactly is happening here?
EDIT
For those interested, here is a jsFiddle link showcasing the problem. While it cannot run due to code size limitations, I've added comments to explain the issue as best as possible.
SECOND EDIT.
To investigate further, console.log() was implemented. One was placed right after
elem.find('.SomeElement').append(el);
, and another console.log('just print this')
inside the directive's controller. It appears that the DOM elements are created before the directive's controller is called. This suggests that all DOM elements are generated before their respective scopes are assigned.
Am I misunderstanding something?