[英]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. 我目前正在使用$ sce.trustAsHtml渲染大量的html和指令。
I used a directive called compile-template which allows me to use ng-directives such as ng-click, and ng-disabled. 我使用了一个名为compile-template的指令,该指令使我可以使用ng-click和ng-disabled等ng指令。
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. 如果对象是静态的(例如名称:'winning'),我可以传递它们,但是如果我使用forEach循环遍历它们,则可以得到
undefined
结果。
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/ 我在这里有一个工作的jsFiddle示例: http : //jsfiddle.net/3J25M/533/
(^open up dev tools to see console.log^) (^打开开发工具以查看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.)
(“ TEST”按钮从forEach循环中获取其对象属性。)
How can i pass in a value using angular.forEach? 如何使用angular.forEach传递值?
Thanks! 谢谢!
Please check working example: Demo 请检查工作示例:演示
Replce your angular.forEach with following code 用以下代码替换您的angular.forEach
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>'
});
What is wrong in your 你怎么了
<button ng-click="fire(a)">TEST</button>
Here you have to replace "fire(a)" with 在这里,您必须将“ fire(a)”替换为
fire( ' + a + ') as you are referring variable
Change your function to access the array, and use the index value from the foreach. 更改函数以访问数组,并使用foreach中的索引值。 This allows access to the scope variable.
这允许访问范围变量。 Notice the value of i and not the string, this is important.
请注意i的值而不是字符串,这很重要。
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])"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.