我可以使用具有隔离作用域的 ng-model 吗? [英] Can I use ng-model with isolated scope?

查看:17
本文介绍了我可以使用具有隔离作用域的 ng-model 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建简单的 ui-datetime 指令.它将 javascript Date 对象拆分为 _date、_hours 和 _minutes 部分._date 使用 jquery ui datepicker、_hours 和 _minutes - 数字输入.

I am creating simple ui-datetime directive. It splits javascript Date object into _date, _hours and _minutes parts. _date uses jquery ui datepicker, _hours and _minutes - number inputs.

angular.module("ExperimentsModule", [])
    .directive("uiDatetime", function () {
    return {
        restrict: 'EA',
        replace: true,
        template: '<div class="ui-datetime">' +
            '<input type="text" ng-model="_date" class="date">' +
            '<input type="number" ng-model="_hours" min="0" max="23" class="hours">' +
            '<input type="number" ng-model="_minutes" min="0" max="59" class="minutes">' +
            '<br />Child datetime1: {{datetime1}}' +
            '</div>',
        require: 'ngModel',
        scope: true,
        link: function (scope, element, attrs, ngModelCtrl) {
            var elDate = element.find('input.date');

            ngModelCtrl.$render = function () {
                var date = new Date(ngModelCtrl.$viewValue);
                var fillNull = function (num) {
                    if (num < 10) return '0' + num;
                    return num;
                };
                scope._date = fillNull(date.getDate()) + '.' + fillNull(date.getMonth() + 1) + '.' + date.getFullYear();
                scope._hours = date.getHours();
                scope._minutes = date.getMinutes();
            };

            elDate.datepicker({
                dateFormat: 'dd.mm.yy',
                onSelect: function (value, picker) {
                    scope._date = value;
                    scope.$apply();
                }
            });

            var watchExpr = function () {
                var res = scope.$eval('_date').split('.');
                if (res.length == 3) return new Date(res[2], res[1] - 1, res[0], scope.$eval('_hours'), scope.$eval('_minutes'));
                return 0;
            };
            scope.$watch(watchExpr, function (newValue) {
                ngModelCtrl.$setViewValue(newValue);
            }, true);
        }
    };
});

function TestController($scope) {
    $scope.datetime1 = new Date();
}

jsfiddle

在 github 上:https://github.com/andreev-artem/angular_experiments/tree/主/用户界面日期时间

On github: https://github.com/andreev-artem/angular_experiments/tree/master/ui-datetime

据我所知 - 创建新组件时的最佳做法是使用隔离作用域.

As far as I understand - best practice when you create a new component is to use isolated scope.

当我尝试使用隔离范围时 - 没有任何效果.ngModel.$viewValue === 未定义.

When I tried to use isolated scope - nothing works. ngModel.$viewValue === undefined.

当我尝试使用新范围时(我的示例,不是很好的变体恕我直言)- ngModel 在新创建的范围上使用值.

When I tried to use new scope (my example, not so good variant imho) - ngModel uses value on newly created scope.

当然,我可以创建具有独立作用域的指令,并通过=expression"(示例).但我认为使用 ngModelController 是更好的做法.

Of course I can create directive with isolated scope and work with ngModel value through "=expression" (example). But I think that working with ngModelController is a better practice.

我的问题:

  1. 我可以使用具有隔离作用域的 ngModelController 吗?
  2. 如果不可能,哪种解决方案更适合创建此类组件?

推荐答案

在你的第一个小提琴中用 scope: { datetime1: '=ngModel'} 替换 scope: true似乎工作正常 - fiddle.不幸的是,指向您的示例"小提琴的链接已损坏,因此我不确定您在那里尝试了什么.

Replacing scope: true with scope: { datetime1: '=ngModel'} in your first fiddle seems to work fine -- fiddle. Unfortunately, the link to your "example" fiddle is broken, so I'm not sure what you tried there.

因此,ngModelController 似乎可以与隔离范围一起使用.

So, it would seem that ngModelController can be used with an isolate scope.

这是一个较小的小提琴,它在 HTML/视图中使用 ng-model、一个隔离范围和链接函数中的 $setViewValue:fiddle.

Here's a smaller fiddle that uses ng-model in the HTML/view, an isolate scope, and $setViewValue in the link function: fiddle.

更新:我刚刚发现了一些相当有趣的东西:如果给隔离范围属性赋予了不同的名称——例如,说 dt1 而不是 datetime1——scope: { dt1: '=ngModel'} -- 它不再起作用了!我猜当我们 require: 'ngModel' 时,ngModelController 使用 HTML/视图中的名称(即 ng-model 属性值)在隔离作用域上创建一个属性.所以如果我们在对象哈希中指定相同的名称,一切都很好.但是如果我们指定一个不同的名称,这个新的范围属性(例如,dt1)就不会与我们需要的 ngModelController 相关联.

Update: I just discovered something rather interesting: if the isolate scope property is given a different name -- e.g., say dt1 instead of datetime1 -- scope: { dt1: '=ngModel'} -- it no longer works! I'm guessing that when we require: 'ngModel', the ngModelController uses the name in the HTML/view (i.e., the ng-model attribute value) to create a property on the isolate scope. So if we specify the same name in the object hash, all is well. But if we specify a different name, that new scope property (e.g., dt1) is not associated with the ngModelController we required.

这是一个更新的小提琴.

这篇关于我可以使用具有隔离作用域的 ng-model 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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