AngularJS-扩展ngModel [英] Angularjs - Extending ngModel
问题描述
下午
ngModelController使您可以控制 $ dirty
和 $ pristine
,但我想拥有自己的一个.我将如何扩展ngModelController以提供类似 ngModelCtrl.$ setCustom()
的东西?
ngModelController gives you control over $dirty
and $pristine
but I would like to have my own one. How would I go about extending the ngModelController to offer something like ngModelCtrl.$setCustom()
?
欢呼
推荐答案
您不能扩展 ngModelDirective
,但是您可以创建自己的 ng-model
.在Angular中相对未知的事情是,您可以有多个具有相同名称的指令,并且所有指令都将被执行.这是一个带有示例的JSBin: http://jsbin.com/nopoyiso/1/edit
You cannot extend ngModelDirective
, but what you can do is create your own ng-model
. It's a relatively unknown thing in Angular that you can have multiple directives with the same name, and all of them will be executed. Here's a JSBin with an example:
http://jsbin.com/nopoyiso/1/edit
对于那些不愿意打开JSBin的人:
And for those who can't be bothered opening the JSBin:
myApp.directive('ngModel', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.setCustom = function() {
console.log('hello!');
}
}
}
});
所以这是一种实现方法,但是我认为这样做最终会使您自己和其他人感到困惑.您能详细说明您要做什么吗?也许有更好的方法来解决这个问题.
So this is a way to do it, but I think you'll end up confusing both yourself and others by doing this. Could you elaborate on what you're trying to do? Perhaps there's a better way to go about it.
这篇关于AngularJS-扩展ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!