我创建了这个非常简单的指令<form-field>
,我试图将ng-model绑定到该指令。我已经将示例分解为最简单的用例,
我已经包含了控制器,以及带有HTML表单的指令。我已经看过许多使用require:ngModel
的示例,然后在link:
内进行操作,但所有这些示例仅适用于dom操作,或者例如不是dom的增量保存值
angular.module('taskApp', [])
.controller('taskController', function($scope) {
$scope.taskData = {};
$scope.save = function(taskData) {
$scope.taskData = angular.copy(taskData);
};
})
.directive('formField', function($timeout) {
var template = '<div class="form-group" ng-switch="element">' +
'<input ng-switch-when="input" ng-model="ngModel" name="{{field}}">' +
'<textarea ng-switch-when="textarea" ng-model="ngModel" name="{{field}}"></textarea>' +
'</div>';
return {
restrict: 'EA',
template: template,
replace: true,
scope: {
ngModel: '=',
field: '@',
live: '@',
element: '@'
},
link: function($scope, element, attr) {
}
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="taskApp" ng-controller="taskController">
<form name='taskForm' novalidate>
<form-field element='input' live='false' field="title" ng-model="taskData.title"></form-field>
<form-field element='textarea' live='false' field="notes" ng-model="taskData.notes"></form-field>
<button type="submit" ng-click="save(taskData)">save</button>
</form>
<br/>
<pre>{{taskData | json}}</pre>
</body>
&#13;
答案 0 :(得分:3)
ngModel
仍然指向内部隔离范围。您可以使用$parent.ngModel
访问外部模型。
var template = '<div class="form-group" ng-switch="element">' +
'<input ng-switch-when="input" ng-model="$parent.ngModel" name="{{field}}">' +
'<textarea ng-switch-when="textarea" ng-model="$parent.ngModel" name="{{field}}"></textarea>' +
'</div>';