我正在从事一个从 JSON 文件中提取大量问题的项目。
问题格式各不相同,但问题是由 slider 问题类型引起的。
我运行 HTTP 请求以获取 JSON 数据并将其分配给名为“问题”的范围。然后我在 View 中重复问题,如果(在这种情况下)问题类型是“ slider ”,我输出 HTML。
问题是 slider 使用插件和带选项的范围变量。因为我无法控制动态创建范围的问题:
angular.forEach($scope.questions, function(question) {
$scope[question.definedScopeName] = {
// set up the slider config.
};
});
JSON 问题包含用于范围的已定义名称,因此对于此示例“sliderOne”。
所以...在我看来,我在 ng repeat 中输出 slider :
<rzslider
class="question__slider"
rz-slider-model="question.definedScopeName.value"
rz-slider-options="question.definedScopeName.options">
</rzslider>
这里的问题是,为了正确设置模型范围,我使用的是来自问题范围的数据,因此它是一个字符串。
无论如何,我可以告诉 Angular 我实际上想将模型设置为名为 $scope.'the defined scope name' 的范围。
谢谢!
最佳答案
在 this
关键字中使用括号表示法
<!--
<rzslider
class="question__slider"
rz-slider-model="question.definedScopeName.value"
rz-slider-options="question.definedScopeName.options">
</rzslider>
-->
<!-- Use bracket notation -->
<rzslider
class="question__slider"
rz-slider-model="this[question.definedScopeName].value"
rz-slider-options="this[question.definedScopeName].options">
</rzslider>
在 Angular Expressions 中,this
关键字绑定(bind)到 Angular Expression 的范围。
关于javascript - Angular 在 View 中使用字符串作为范围属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206387/