我可以用NG-模型孤立的范围是什么? [英] Can I use ng-model with isolated scope?

查看:84
本文介绍了我可以用NG-模型孤立的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建简单的UI,日期时间指令。它分割的JavaScript Date对象为_date,_hours和_minutes部分。 _date使用jQuery UI的日期选择器,_hours和_minutes - 数字输入

  angular.module(ExperimentsModule,[])
    .directive(uiDatetime功能(){
    返回{
        限制:EA,
        更换:真实,
        模板:'< D​​IV CLASS =UI-日期时间>' +
            '<输入类型=文本NG模型=_日期级=日期>' +
            '<输入类型=数字NG-模式=_小时最小=0最大=23级=小时>' +
            '<输入类型=数字NG-模式=_分钟分钟=0最大=59级=分钟>' +
            '< BR />儿童datetime1:{{datetime1}}'+
            '< / DIV>,
        要求:'ngModel',
        适用范围:真,
        链接:功能(范围,元素,ATTRS,ngModelCtrl){
            变种elDate = element.find('input.date');            ngModelCtrl。$ =渲染功能(){
                VAR日期=新的日期(ngModelCtrl $ viewValue);
                VAR fillNull =功能(NUM){
                    如果(NUM小于10)返回'0'+ NUM;
                    返回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:函数(值,选择器){
                    scope._date =价值;
                    。范围$适用();
                }
            });            VAR watchExpr =功能(){
                VAR解析度= $范围的eval('_日期)拆分('。')。
                如果(res.length == 3)返回新的日期(RES [2],资源[1] - 1,RES [0],$范围的eval('_小时),范围$的eval('_分钟)) ;
                返回0;
            };
            范围。$腕表(watchExpr,功能(newValue)以{
                ngModelCtrl $ setViewValue(newValue)以。
            },真正的);
        }
    };
});功能的TestController($范围){
    $ scope.datetime1 =新的日期();
}

<大骨节病>的jsfiddle

在GitHub上:<一href=\"https://github.com/andreev-artem/angular_experiments/tree/master/ui-datetime\">https://github.com/andreev-artem/angular_experiments/tree/master/ui-datetime

据我的理解 - 最佳实践当你创建一个新的组件是用隔离范围

当我试图用孤立的范围 - 没有什么作品。 ngModel。$ viewValue ===不确定的。

当我试图用新的作用域(我的例子,不是那么好变种恕我直言) - ngModel对新创建的范围使用值

我当然可以通过=前pression(<一个孤立的工作范围和与ngModel价值创造指令href=\"https://github.com/andreev-artem/angular_experiments/blob/uiDatetime_impl2/ui-datetime/ui-datetime.js\">example).但我认为,随着ngModelController工作是一个更好的做法。

我的问题:


  1. 我可以使用ngModelController孤立范围?

  2. 如果这是不可能其中溶液是用于创建这样的组件更好?


解决方案

更​​换范围:真正的范围:{datetime1:'= ngModel } 在您的第一提琴似乎做工精细 - 小提琴。不幸的是,链接到你的榜样捣鼓坏了,所以我不知道你尝试过那里。

所以,它似乎ngModelController可以与分离范围内使用。

下面是一个使用NG-模型在HTML /视图较小的小提琴,一个隔离范围和$ setViewValue在链接功能:小提琴

更新:我刚刚发现相当有趣的事情:如果分离的范围属性被赋予了不同的名称 - 例如,说DT1而不是datetime1 - 范围:{DT1 :'= ngModel'} - 它不再起作用!我猜,当我们要求:ngModel中,ngModelController在HTML /视图使用的名称(即NG-model属性值)来创建一个属性在分离范围。因此,如果我们在对象哈希指定同一名称,一切都很好。但是,如果我们指定一个不同的名称,新的作用域属性(例如,DT1)未与我们所需要的相关ngModelController

下面是一个更新拨弄

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

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.

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

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

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.

My questions:

  1. Can I use ngModelController with isolated scope?
  2. If it is not possible which solution is better for creating such component?

解决方案

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.

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

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

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.

Here's an updated fiddle.

这篇关于我可以用NG-模型孤立的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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