添加ngModel输入一个指令 [英] Adding ngModel to input with a directive

查看:94
本文介绍了添加ngModel输入一个指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入的元素,我想使用自定义指令到ngModel和ngClass绑定到它,但我有一些麻烦。

I have an input element and I would like to bind a ngModel and a ngClass to it using a custom directive, but I'm having some troubles.

我有什么:

<input type="text" myDirective="PropertyFromScope" />

我要为结果是什么:

What I want as result:

<input type="text" ng-model="PropertyFromScope" ng-class="{'class' : MethodFromScope}" />

我试图避免使用模板,因为我想指令与任何输入标签的工作。

I'm trying to avoid using templates, because I want the directive to work with any input tag.

下面是我走到这一步:

angular.module('customDirectives', [])
.directive('myDirective', function () {
    var linker = function (scope, element, attrs) {
        attrs.$set('ngModel', attrs.myDirective);
        attrs.$set('ngClass', '{\'class\' : MethodFromScope}');
    }
    return {
        restrict: 'A',        
        link: linker
    }
});

下面是一个的jsfiddle: http://jsfiddle.net/Q8QJJ/

Here's a JSFiddle: http://jsfiddle.net/Q8QJJ/

推荐答案

您想做到这一点?

pretty简单的解决方案:

Pretty simple solution:

myApp.directive('myDirective', function ($compile) {
    return {
        restrict: 'A',        
        compile: function(element, attrs) {
            element.attr('ng-model', attrs.myDirective);
            element.removeAttr("my-directive");
            element.attr('ng-class', '{\'class\' : testFunction()}');
            return {
               pre: function preLink(scope, iElement, iAttrs, controller) { },
               post: function postLink(scope, iElement, iAttrs, controller) { 
                 $compile(iElement)(scope);
               }
            }
        }
    }
});

下面是一个小提琴 http://jsfiddle.net/V9e9M/

这篇关于添加ngModel输入一个指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆