使用指令将ngModel添加到角度datepicker输入

时间:2014-03-17 10:08:24

标签: javascript angularjs datepicker directive angular-ngmodel

我正在尝试创建一个使用包含属性和验证等的模式对象生成的UI。我需要使用指令作为结果在我的ui控件上设置ngModel。 ngModel的值是一个字符串,表示作用域上架构对象的属性路径。

我对标准输入有效,但使用angular ui datepicker时会出现以下错误。

Error: [$compile:ctreq] Controller 'ngModel', required by directive 'myModel', can't be found!
http://errors.angularjs.org/1.2.10/$compile/ctreq?p0=ngModel&p1=myModel
at http://localhost:3000/javascripts/angular.js:78:20
at getControllers (http://localhost:3000/javascripts/angular.js:6054:39)
at nodeLinkFn (http://localhost:3000/javascripts/angular.js:6225:55)
at compositeLinkFn (http://localhost:3000/javascripts/angular.js:5634:37)
at compositeLinkFn (http://localhost:3000/javascripts/angular.js:5637:33)
at compositeLinkFn (http://localhost:3000/javascripts/angular.js:5637:33)
at publicLinkFn (http://localhost:3000/javascripts/angular.js:5539:46)
at boundTranscludeFn (http://localhost:3000/javascripts/angular.js:5653:37)
at controllersBoundTransclude (http://localhost:3000/javascripts/angular.js:6245:36)
at Object.ngIfWatchAction [as fn] (http://localhost:3000/javascripts/angular.js:18316:29)

<input class="form-control" datepicker-popup="dd-MMM-yyyy" my-model="" is open="property.calOpen" close-text="Close" ng-model="editModel.Person.Detail.DateOfBirth">

我的指示如下。

angular.module('MyDirectives',[])
.directive('myModel', function($compile , $timeout) {
    return {
        restrict: 'A',                       
        priority:0,

        link: function(scope,element, attr) {

            if(angular.isDefined(attr.ngModel))return;
            var field = scope.path ? scope.path + '.' + scope.key : scope.key;
            attr.$set("ngModel", "editModel." + field);

            console.log("in directive");
            $timeout(function(){
                $compile(element)(scope);
            });
        }
    };

由于ngModel的值存在于作用域上,我相信我需要链接函数而不是编译。我已经尝试将Require: ?ngModel添加到指令中,这没有任何区别。也尝试增加优先级,但这会改变错误 Error: [$compile:ctreq] Controller 'ngModel', required by directive 'input', can't be found!

如果我移除$timeout(function(){}周围$compile(element)(scope) 2个弹出式日历,则会显示重叠的日历。导航数月时,这是显而易见的。

任何想法

更新:请参阅链接 plkr

1 个答案:

答案 0 :(得分:1)

您需要创建一个与局部范围变量的新的双向绑定(范围:true) 使用$ parse在路径中找到属性。

请参阅updated Plunker