动态NG-model的指令内结合 [英] Dynamic ng-model binding inside a directive

查看:106
本文介绍了动态NG-model的指令内结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个使用动态NG-模型内而外的指令自定义组件。

I'm trying to create a custom component that uses a dynamic ng-model inside-out the directive.

作为一个例子,我可以调用不同的组件,如:

As an example, I could invoke different components like:

<custom-dir ng-model="domainModel1"></custom-dir>
<custom-dir ng-model="domainModel2"></custom-dir>

通过一项指令,如:

app.directive('customDir', function() {
  return {
    restrict: 'EA',
    require: '^ngModel',
    scope: {
      ngModel: '=dirValue',
    },
    template: '<input ng-model="dirValue" />',
    link: function(scope, element, attrs, ctrl) {
      scope.dirValue = 'New';
    }
  };
});

的想法是,如果模型变化,并且在周围的其他方式从该指令的文本框将改变。

The idea is that the textbox from the directive would change if the model changes, and in the other way around.

的事情是,我已经尝试了不同的方法没有成功可言,你可以检查这个位置之一:<一个href=\"http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=$p$pview\">http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=$p$pview在这个例子中,我期待有两个输入的值'新',因为我改变从该指令模式,必将是一个双向(=)。但不知何故,没有以正确的方式约束。 (

The thing is that I've tried different approaches with no success at all, you can check one of this here: http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=preview In this example, I'm expecting to have the value 'New' in both of the inputs, since I'm changing the model from the directive and is a bi-directional bound (=). But somehow is not bound in the right way. :(

我将非常感激,如果有人给上一些轻。在此先感谢!

I will be really grateful if someone give some light on that. Thanks in advance!

推荐答案

这样呢?

http://jsfiddle.net/bateast/RJmhB/1/

HTML

<body ng-app="test">
    <my-dir ng-model="test"></my-dir>
    <input type="text" ng-model="test"/>
</body>

JS:

angular.module('test', [])
    .directive('myDir', function() {
        return {
            restrict: 'E',
            scope: {
                ngModel: '='
            },
            template: '<div><input type="text" ng-model="ngModel"></div>',            
        };
    });

这篇关于动态NG-model的指令内结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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