[英]Adding Dynamic Radio Buttons in Angular
I'm working in Angular with just a plain old JS function that returns a list of data from an API. 我在Angular中工作的只是一个普通的旧JS函数,该函数从API返回数据列表。 I then turn the data into radio buttons like this:
然后,我将数据变成如下所示的单选按钮:
function parseRoles(jsonObj) {
console.log("passed: " + jsonObj);
var tempRoleArray = [];
for (var i = 0; i < jsonObj.role.length; i++) {
tempRoleArray.push("<input type='radio' ng-model='user.role' value='" + jsonObj.role[i].role + "'>" + jsonObj.role[i].description + " ");
}
$("#userRoleEntry").html(tempRoleArray);
}
Works great from the JS side but then the Angular side doesn't recognize "user.role" or "$scope.user.role" with "not defined" errors for each. 从JS端工作得很好,但是Angular端无法识别出每个都有“未定义”错误的“ user.role”或“ $ scope.user.role”。 Is this because this input is a little different in the partial?
这是因为此输入在部分输入方面有些不同吗? Something else?
还有吗 Seems to be some questions alluding to Angular not really doing these kinds of things all that well... EDIT: This is not the only input in the form.
似乎是一些问题暗示了Angular并没有真正做好这些事情……编辑:这不是表单中的唯一输入。 The rest of them have been collected or returned from the API.
其余的已从API收集或返回。 So not sure I can compile against scope and seems like kind of an overkill answer.
因此,不确定我是否可以针对范围进行编译,似乎有点过分回答。 I could be wrong about that, of course.
我当然可能是错的。
woou, I would better change the API instead of adding $compile
to your JS code! woou,我最好更改API,而不是在您的JS代码中添加
$compile
!
The API should return the jsonObj
and than you can easily build your View in Angular. API应该返回
jsonObj
然后您可以轻松地在Angular中构建View。
Also it is not the Angular-way to do something like this: 也不是做这样的事情的Angular方法:
$("#userRoleEntry").html(tempRoleArray);
I assume that your JSON looks like this: An array with Objects. 我假设您的JSON如下所示:带对象的数组。
$scope.roles = [{role: 'test', description: 'text'}]; // your "jsonObj.role"
Then your HTML should look like this: 然后,您的HTML应该如下所示:
<div ng-repeat="obj in roles">
<input type="radio" ng-model="user.role" ng-value="obj.role"> {{obj.description}}
</div>
You need to compile the DOM element in order to have angular pick it up. 您需要编译DOM元素才能使它有角度地拾取它。
See doc for examples: https://docs.angularjs.org/api/ng/service/$compile 有关示例,请参见文档: https : //docs.angularjs.org/api/ng/service/$compile
As @pankajparkar points out, you can do $compile($("#userRoleEntry"))($scope)
to compile your element. 正如@pankajparkar指出的那样,您可以执行
$compile($("#userRoleEntry"))($scope)
来编译您的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.