【问题标题】:Adding ngModel to angular datepicker input using a directive使用指令将 ngModel 添加到角度日期选择器输入
【发布时间】:2014-04-22 11:44:33
【问题描述】:

我正在尝试创建一个使用包含属性和验证等的模式对象生成的 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

【问题讨论】:

  • 小提琴怎么样...?
  • plnkr 添加,见链接。
  • 对不起,但它太乱了(据我所知)。您正在循环使用您的模板。并且稍后添加ngModel(意味着在编译其他指令(例如datapicker)之后)也无济于事。我建议您尝试(很多)简化事情(尽管我不确定具体如何)。对不起,我帮不上忙:)
  • 谢谢,但这对我没有任何帮助。每当我需要动态设置 ng-model 时,我都会遇到这个问题,其中使用了需要 ng-model 值的其他指令。#help!
  • 如果有一个需要 ngModel 的指令,你可以尝试让它的编译函数添加 ngModel 指令(但它必须在 ngModel 编译之前运行 - 你必须查看优先级)。

标签: javascript angularjs datepicker directive angular-ngmodel


【解决方案1】:

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

updated Plunker

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多