Search code examples
angularjsui-select2angularjs-select2

ui-select2 and ng-required


I'm having problems using require/ng-require with the ui-select2 component. I wrapped the ui-select2 in a custom directive for reasons of reusability, but can't get the required to work with it.

This is the plunker: http://plnkr.co/edit/2NaGvDWoEw14BN2few9W?p=preview

Tried without the directive and it's working: http://plnkr.co/edit/uE698iFcUNnsYVF2fkOO?p=preview


Solution

  • The Problem was that angular dosn't support dynamic form element:

    Issue #1404 https://github.com/angular/angular.js/issues/1404

    Workaround (till 1.3 is out):

    app.config(['$provide', function($provide) {
    $provide.decorator('ngModelDirective', ['$delegate', function($delegate) {
        var ngModel = $delegate[0], controller = ngModel.controller;
        ngModel.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
            var $interpolate = $injector.get('$interpolate');
            attrs.$set('name', $interpolate(attrs.name || '')(scope));
            $injector.invoke(controller, this, {
                '$scope': scope,
                '$element': element,
                '$attrs': attrs
            });
        }];
        return $delegate;
    }]);
    $provide.decorator('formDirective', ['$delegate', function($delegate) {
        var form = $delegate[0], controller = form.controller;
        form.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
            var $interpolate = $injector.get('$interpolate');
            attrs.$set('name', $interpolate(attrs.name || attrs.ngForm || '')(scope));
            $injector.invoke(controller, this, {
                '$scope': scope,
                '$element': element,
                '$attrs': attrs
            });
        }];
        return $delegate;
    }]);
    

    Source: http://jsfiddle.net/Thinkscape/23RPt/