Javascript 将JSON解析为指令
基本上,我对我的页面及其各自的模板使用角度路由。每个页面都有一个表单,其中包含更多的HTML字段(输入/选择/文本区域)。我正在尝试创建可重用指令来创建html字段,如下所示Javascript 将JSON解析为指令,javascript,jquery,html,json,angularjs,Javascript,Jquery,Html,Json,Angularjs,基本上,我对我的页面及其各自的模板使用角度路由。每个页面都有一个表单,其中包含更多的HTML字段(输入/选择/文本区域)。我正在尝试创建可重用指令来创建html字段,如下所示 app.directive('field',function(){ return { restrict : "E", scope : { }, link : function(scope,elem,attr){
app.directive('field',function(){
return {
restrict : "E",
scope : {
},
link : function(scope,elem,attr){
var content;
scope.Options = {
id: scope.$id+'_'+elem.attr('id'),
label : elem.attr('label'),
placeholder : elem.attr("placeholder"),
};
scope.contentUrl = 'templates/fields/'+elem.attr('template')+'.html';
},
template: '<div ng-include="contentUrl"></div>'
}
})
客户控制器
app.controller('customerController', ['$scope', 'dataService',function($scope,dataService) {
dataService.getCustomerData();//need to parse this data into field directive
}]);
我这样做对吗?我们如何将各自的页面数据解析到由指令创建的页面字段中?首先,我认为您需要将获取的数据与控制器的作用域绑定:
app.controller('customerController', ['$scope', 'dataService',function($scope,dataService) {
dataService.getCustomerData().then(function ( data ) {
$scope.data = data; // let data == { someField: 42 }
};
}]);
然后,您需要将范围中的数据使用到angular的模板中:
<field id="NAME" template="text" label="First Name" placeholder="Enter First Name">{{someField}}</field>
{{someField}
要预填充字段,需要使用角度绑定,即ngModel
。在指令中使用ng include
是多余的,您可以直接在指令中使用模板属性
我会这样做:
app.directive('customtext',function() {
return {
restrict:'E',
require:'ngModel',
scope:{
thevalue:'='
},
template:'<input type="text" ng-model="thevalue"/>',
}
});
您需要为要创建的每个字段创建一个指令
ps:通过$http获取的JSON会自动转换为对象。您不需要使用JSON.parse
<field id="NAME" template="text" label="First Name" placeholder="Enter First Name">{{someField}}</field>
app.directive('customtext',function() {
return {
restrict:'E',
require:'ngModel',
scope:{
thevalue:'='
},
template:'<input type="text" ng-model="thevalue"/>',
}
});
<customtext thevalue="name" />
app.controller('customerController', ['$scope','dataService',function($scope,dataService) {
var data = dataService.getCustomerData();
$scope.name = data.name;
}]);