在指令的嵌套 ngModel 中控制 $viewValue 的设置 [英] Control the setting of $viewValue in a directive's nested ngModel

查看:28
本文介绍了在指令的嵌套 ngModel 中控制 $viewValue 的设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的 UI 控件,我将其建模为指令,它是一个电话号码编辑器,具有两个输入字段:一个用于国家/地区代码,另一个用于号码.

指令的用法如下所示:

在指令的声明中,我需要 ngModel 并且模板如下所示:

<input type="text" ng-model="number"/>

很清楚如何将原始模型组合和分解为两个字段.

我无法弄清楚的是 - 我如何为第二个字段使用格式化程序,以便它显示 (555) 555-5555 而不是普通数字,而无需定义另一个指令来访问第二个输入字段的 ngModel 控制器?

我可以以某种方式访问​​子 ngModel 控制器吗?

解决方案

我做了一些在 Angular 代码库上搜索 并找到了一些应该可以工作的东西:

app.directive('phoneEditor', function() {返回 {限制:'E',替换:真的,模板:'

'+ ''+ ''+ '</div>',链接:函数(范围,元素){scope.number = 555;var input1 = element.find('input').eq(0);var input2 = element.find('input').eq(1);input1Ctrl = input1.controller('ngModel');input2Ctrl = input2.controller('ngModel');控制台日志(输入1Ctrl,输入2Ctrl);}};});

Plunker.

I have a fairly simple UI control that I've modeled as a directive, which is an editor for phone numbers that has two input fields: one for the country code and another for the number.

The directive's usage looks like this:

<phone-editor ng-model='phoneNo'></phone-editor>

In the directive's declaration, I require ngModel and the template looks like this:

<input type="text" ng-model="countryCode" />
<input type="text" ng-model="number" />

It's clear how to compose and decompose the original model into the two fields.

What I cannot figure out is - how do I use a formatter for the second field such that it displays (555) 555-5555 instead of the plain number, without defining another directive just to access the ngModel controller of the second input field?

Can I somehow access the child ngModel controller?

解决方案

I did a few searches on the Angular codebase and found something that should work:

app.directive('phoneEditor', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div>'
      + '<input type="text" ng-model="countryCode">'
      + '<input type="text" ng-model="number">'
      + '</div>',
    link: function(scope, element) {
      scope.number = 555;
      var input1 = element.find('input').eq(0);
      var input2 = element.find('input').eq(1);
      input1Ctrl = input1.controller('ngModel');
      input2Ctrl = input2.controller('ngModel');
      console.log(input1Ctrl, input2Ctrl);
    }
  };
});

Plunker.

这篇关于在指令的嵌套 ngModel 中控制 $viewValue 的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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