指令中需要AngularJS设置输入

时间:2014-11-24 01:48:20

标签: angularjs angularjs-directive angularjs-compile

我需要动态地创建一个输入字段(或不需要),并希望在指令中设置此值。我知道有ng-required指令,可以设置为ng-required =“datamodel.required”但最终,我想在指令中提取一个设置对象,并根据该配置打开/关闭所需的参数。配置是在服务中,我不想为每个表单控制器注入服务 - 因此我需要在指令中设置它。

这是JSFiddle的起点: http://jsfiddle.net/hm2b771z/2/

app.directive('requiredConfig', function($compile){
    return {
        link: function(scope, element, attrs){
            console.log(attrs.requiredConfig);
            console.log(attrs.ngRequired);
            attrs.ngRequired = (attrs.requiredConfig == "true") ? true : false;
            $compile( element.contents() )( scope );
            console.log(attrs.ngRequired);
            console.log('_______________________');
        }
    }
});

我期望的是作为第一个字段选项的字段,而第二个字段选项仍然是可选的。

谢谢!

2 个答案:

答案 0 :(得分:0)

而不是

attrs.required = (attrs.requiredConfig == "true") ? true : false;

使用

if (attrs.requiredConfig == "true"){
    element.attr('required', 'true');
}

答案 1 :(得分:0)

这是我最后做的事,感谢Angular directive how to add an attribute to the element?

angular.module( 'app' )
.directive
(
    'requiredByConfig',
    function( $compile, Utils ){
        var directive = {
            terminal: true,
            priority: 1001,
            compile: function( element, scope ){
                var configKey = element.attr( 'required-by-config' );
                var req = Utils.getRequiredFromConfig(configKey) // Injected;

                // Remove this directive in order to avoid infinite compile loop.
                element.removeAttr( 'required-by-config' );

                // Add the required directive with the required value.
                element.attr( 'ng-required', req );

                // Compile the new directive
                $compile( element.contents() )( scope );

                var fn = $compile( element );
                return function( scope ){
                    fn( scope );
                };
            }
        };

        return directive;
    }
);

然而,更好的解决方案是使用过滤器:

angular.module( 'app' ).filter
( 'requiredByConfig',
    function( Utils ){
        return function( initialValue, configKey, visible ){
            if( angular.isDefined( visible ) && !visible ){
                // If the input is hidden, we don't want to require it.
                return false;
            }

            // Get the config setting. If available, overwrite the default.
            if( angular.isDefined( Utils.SETTINGS[ configKey ] ) ){
                // A config exists for this field. Return the value of the config.
                return Utils.getBoolean( Utils.SETTINGS[ configKey ] );
            } else {
                // Return the initial required value
                return initialValue;
            }
        }
    }
)