gpt4 book ai didi

javascript - 我如何将数据绑定(bind)到 angularjs 中的该指令

转载 作者:行者123 更新时间:2023-12-02 14:03:23 24 4
gpt4 key购买 nike

我创建了一个指令,它将在 html 模板中显示替代问题:

app.directive('altQuestion', ['$http', function($http) {
'use strict';
var directive = {
restrict: 'E',
transclude: true,
scope: {
json: '@',
data: '='
},
template: function() {
return '<div ng-repeat="item in questionData" name="{{item.key}}" class="{{item.class}}"> '+
'<label class="labelHeading"> '+
'{{item.labelHeading}} '+
'</label> '+
'<span ng-repeat="q in item.questions"> '+
'<label>{{q.label}}</label> '+
'<input '+
'type="{{q.type}}" '+
'name="{{item.key}}" '+
//'ng-model="{{item.data}}" '+
'value="{{q.value}}" '+
'required'+
'/> '+
'</span> '+
'</div>';
},
link: link
};
return directive;
function link(scope, elem, attr) {
$http.get('/json/alt_questions.json').
then(function(json) {

scope.questionData = json.data;
//console.log(scope.data);
angular.forEach(scope.questionData, function (v, i) {
angular.forEach(scope.data, function (k, index) {
if (v.key === index) {
console.log(v.data);
}
});
});
});

}
}]);

我需要绑定(bind)的数据在

scope.data

json 中的问题信息如下所示:

[{
"key": "head_brain",
"dependent": "",
"data": "visit.data.head_brain",
"class": "optionBox",
"labelHeading": "Head/brain injuries or illnesses?",
"questions": [{
"label": "No",
"value": "0",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Yes",
"value": "1",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Not Sure",
"value": "2",
"type": "radio",
"req": true,
"dis": false
}],
"comments": "",
"commentKey": ""
}, {
"key": "seizures",
"dependent": "",
"data": "visit.data.seizures",
"class": "optionBox",
"labelHeading": "Seizures or Epilepsy?",
"questions": [{
"label": "No",
"value": "0",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Yes",
"value": "1",
"type": "radio",
"req": true,
"dis": false
}, {
"label": "Not Sure",
"value": "2",
"type": "radio",
"req": true,
"dis": false
}],
"comments": "",
"commentKey": ""
}]

我需要将生成的每个问题的scope.data 绑定(bind)到ng-model。我会在表单上创建一个 angular.each 吗?我怎样才能在隔离范围内做到这一点?

这是一个骗子:http://plnkr.co/edit/REOg53RgGUwb0OF3Fn1f

plunker 中需要发生的是,在根据主 Controller 中传递到隔离范围的数据集加载时,需要选择单选按钮。

最佳答案

有两种方法可以做到这一点。稍加修改: http://plnkr.co/edit/nSUb6WH5B9xD3fFnklc9?p=preview

'ng-model="$parent.$parent.$parent.visit.data[item.data]"

这里需要三个 $parent,因为您想要超出隔离范围。为此,您需要访问 $parent 作用域,但是两个 ng-repeats 创建了它们自己的作用域,因此指令的真正父作用域将是 $parent.$parent.$parent。

更好的方法是避免这种直接使用并提供模型作为属性,如第二个示例中所示 http://plnkr.co/edit/QDhpb9DgUMaUBdQVO79q?p=preview

scope.$parent.$watch(attr.model, function(newVal) {
scope.model = newVal;
});

然后,按如下方式使用它:

'ng-model="model[item.data]" '

关于javascript - 我如何将数据绑定(bind)到 angularjs 中的该指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com