【发布时间】:2018-06-11 21:27:31
【问题描述】:
我正在尝试为表单中的自定义字段创建指令。我可以创建指令但无法更新范围。
请参阅Plunker 演示以了解有关问题的更多想法
问题我面临的是当我提交表单时,我得到的自定义字段 ng-model 的值为 null 或未定义。因为双向绑定不起作用
您会看到,当我们从父范围更新范围时,它会更新指令范围,但是当您在自定义字段中更新它时,它不会更新使用父范围的输入字段,之后两种方式绑定将不起作用
这是我的文件
users.html
<custom-field ng-repeat="(key,field) in custom_fields" form="userForm" ng-model="user.custom_field[field.id]" fielddata="field"></custom-field>
app.js
app.directive('customField', function () {
var directive = {};
directive.restrict = 'E';
directive.templateUrl = 'app/modules/custom_fields/views/custom_field_directive.html';
directive.scope = {
ngModel: "=",
mydata: "<fielddata",
form: "<"
}
return directive;
});
custom_field_directive.html
<div layout="row" layout-xs="column">
<div flex >
<!-- Custom input field html [Required Field] -->
<md-input-container class="md-block" ng-if="mydata.type == 'input' && mydata.is_required==1">
<label>{{mydata.field_name}}</label>
<input name="{{mydata.slug}}" ng-model="ngModel" ng-required="!ngModel">
<div ng-messages="form[''+mydata.slug+''].$error" ng-show="form[''+mydata.slug+''].$touched" role="alert">
<div ng-message="required">
<span>{{mydata.field_name}} is required</span>
</div>
</div>
</md-input-container>
<!-- Custom input field html -->
<md-input-container class="md-block" ng-if="mydata.type == 'input' && mydata.is_required==0">
<label>{{mydata.field_name}}</label>
<input name="phone" ng-model="ngModel">
</md-input-container>
</div>
</div>
从数据库中获取自定义字段值的函数UsersController.js
$scope.getCustomFields = function (id = "") {
$rootScope.loader = true;
$http.post(site_settings.api_url + 'get_custom_fields_admin_user', {id: id})
.then(function (response) {
$scope.custom_fields = response.data;
angular.forEach($scope.custom_fields, function (value, key) {
if (value.field_values) {
$scope.user.custom_field[value.id] = value.field_values.value;
console.log("in");
} else {
$scope.user.custom_field[value.id] = null;
}
});
$rootScope.loader = false;
}).catch(function (error) {
$rootScope.message = 'Something Went Wrong.';
$rootScope.$emit("notification");
$rootScope.loader = false;
});
}
这是我在提交表单时得到的用户模型
演示
【问题讨论】:
标签: javascript html angularjs angularjs-directive angularjs-scope