jward01 jward01 - 5 months ago 10
jQuery Question

How can I pass using a for-loop in an Angular object to a string that gets rendered by $sce

I am currently rendering a chunk of html and directives using $sce.trustAsHtml.

I used a directive called compile-template which allows me to use ng-directives such as ng-click, and ng-disabled.

I am able to pass in objects if they are static (such as name: 'winning'), BUT if I am cycling through them using a forEach loop, i get an

undefined
result.

Example:

$scope.xxx = {
name: "winning",
array:["test","123","456","888"]
};

var string = 'I am an <code>HTML</code>string with <a href="#" ng-mouseover="removeExp()">links!</a> and other <em>stuff</em> <button ng-click="fire(a)">TEST</button>'
angular.forEach($scope.xxx.array, function (a) {

string += 'I am an <code>HTML</code>string with <a href="#" ng-mouseover="removeExp()">links!</a> and other <em>stuff</em> <button ng-click="fire(a)">TEST</button> <button ng-click="works(xxx.name)">Works</button>'
});



$scope.myHTML =$sce.trustAsHtml(string);


I have a working jsFiddle example here: http://jsfiddle.net/3J25M/533/

(^open up dev tools to see console.log^)

Notice how the 'Works' button does work, but the 'TEST' button does not. (the 'TEST' button gets its object property from a forEach loop.)




How can i pass in a value using angular.forEach?

Thanks!

Answer

Change your function to access the array, and use the index value from the foreach. This allows access to the scope variable. Notice the value of i and not the string, this is important.

angular.forEach($scope.xxx.array, function (a, i) {

  string += 'I am an <code>HTML</code>string with <a href="#" ng-mouseover="removeExp()">links!</a> and other <em>stuff</em> <button ng-click="fire(xxx.array[' + i + '])">TEST</button> <button ng-click="works(xxx.name)">Works</button>'
});

For instance, it will generate the following:

ng-click="fire(xxx.array[0])"
Comments