这听起来很奇怪,但是,即使这是不好的做法或其他什么,我怎么能得到这个:
html:
<div ng-controller='CtrlCtrl as ctrlr'>
<input account />
<button ng-disabled='ctrlr.isValid()'>Click</button>
</div>
看起来像这样:
目标:
<div ng-controller='CtrlCtrl as ctrl'>
<input type='text' name='derp_herp' ng-model='ctrlr.goal'
ng-maxlength='10' ng-minlength='3' ng-required='true'
ng-pattern='/^\d+$/' ng-focus='ctrlr.action()' ng-blur='ctrlr.validate()'
ng-change='ctrlr.checkValid()'
/>
</div>
如果不这样做:
app.directive('accounts', [function() {
return {
restrict: 'A',
scope: {},
transclude: true,
templateUrl: 'inpt.html', // <==== no.
// template: 'the contents of inpt.html' <==== no.
link: function(scope, elem, attrs, model) {
//this is where things vary.
}
}
.
.
.
我尝试过的一些事情- (plunkr)
假设这部分是恒定的:
function action(a, b, c){ alert(a); alert(b); alert(c); }
app.directive('accounts', ['$compile', function($compile) {
return {
require: 'ngModel',
restrict: 'A',
scope: {},
transclude: true,
link: function(scope, elem, attrs, model) {
//this is where things vary.
}
}
}]);
.
.
.
以下内容的每次迭代(注释掉等):
var a, b, c;
attrs.ngPattern = /^\d+$/;
attrs.ngMinlength = '3';
attrs.ngMaxlength = '10';
attrs.ngChange = function(){
a= Object.keys(model);
b= Object.keys(elem);
c= Object.keys(attrs);
action(a, b, c );
}
$compile(attrs);
$compile(elem)
$compile(scope)
和:
var a, b, c;
if(model.$invalid){
elem.addClass('test');
}
attrs.$set('ngMinlength', '3')
attrs.$set('ngMaxlength', '3')
attrs.$set('ngPattern', /^\d+$/);
$attrs.$set('ngChange','action()');
$compile(attrs);
$compile(elem)
$compile(scope)
并尝试使用控制器
app.controller("CtrlCtrl", ['$scope', '$element','$attrs', '$compile',
function ($scope, $elem, $attrs, $compile) {
var meta = this, a, b,c;
this.meta = meta;
this.ctrlr = meta || {}
this.ctrlr.modl = "abc";
$attrs.$set('ngMinlength', '3')
$attrs.$set('ngMaxlength', '10')
$attrs.$set('ngPattern', /^\d+$/);
a= Object.keys($scope);
b= Object.keys($elem);
c= Object.keys($attrs);
$attrs.$set.ngChange = function(){
action(a, b, c );
}
$compile($scope);
$compile($attrs);
$compile($elem)
$compile($scope)
// console.log(a);
// console.log(b);
// console.log(c);
}
]);
我不知道为什么这很困难。文档起初似乎足够详细,但天哪,一旦您进入战壕,这还不够。我看过每个 egghead.io 视频,读了很多东西……认真的。如果这是另一种语言,我现在就会教它。