我正在尝试创建一个指令以在表单中重用。但是当我提交时,输入(指令)不存在。
这是我的标签:
<core-input type="text" icon="person" name="name" placeholder="Name" ng-model="mymodel.name"></core-input>
这是我的指令js代码:
angular.module('StarterApp').directive('coreInput', function($compile) {
return {
restrict: 'AE',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
scope.onChange = function() {
ngModel.$setViewValue(scope.value);
};
ngModel.$render = function() {
scope.opts = attrs;
scope.value = ngModel.$modelValue;
$compile(element.contents())(scope);
};
},
templateUrl: function(elem, attr) {
return './app/views/directives/form/' + attr.type + '.html';
}
};
});
这就是我想要重用的东西:
<md-input-container class="md-icon-float md-block" flex-gt-sm md-no-float>
<md-icon class="material-icons">
<i class="material-icons">{{ opts.icon }}</i>
</md-icon>
<input type="text" name="{{ opts.name }}" placeholder="{{ opts.placeholder }}" ng-model="$parent.ngModel">
</md-input-container>
我在这里缺少什么?
答案 0 :(得分:0)
angular文档声明$ setViewValue不会在ngModel上调用$ render方法。所以这必须手动调用。由于元素的html已经改变,因此可以从角度服务中检索原始模板$ templateCache
var urlPrefix = './app/views/directives/form/';
var templateExtension = '.html';
angular.module('StarterApp').directive('coreInput',['$compile', '$templateCache' function($compile, $templateCache) {
return {
restrict: 'AE',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
scope.onChange = function() {
ngModel.$setViewValue(scope.value);
ngMode.$render();
};
ngModel.$render = function() {
var template = $templateCache.get(urlPrefix + attrs.type + templateExtension);
element.html(template);
$compile(element.contents())(scope);
};
},
templateUrl: function(elem, attr) {
return urlPrefix + attr.type + templateExtension;
}
};
}]);