AngularJS - 指令以纳克-transclude,无双向绑定 [英] AngularJS - directive with ng-transclude, no two-way binding

查看:187
本文介绍了AngularJS - 指令以纳克-transclude,无双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见演示

<body ng-controller="MainCtrl">

    {{ obj }}

    <dir>
      <input type="text" ng-model="obj" />
    </dir>

  </body>

为什么当我改变自定义指令中的 OBJ 范围变量, NG-transclude 我不改变它在 MainCtrl $ scope.obj

Why when I change the obj scope variable in the custom directive with ng-transclude I don't change it in the MainCtrl $scope.obj.

但是,当我有 $ scope.obj = {名称:'测试'}; MainCtrl 两-way绑定工作,我期望的方式。

But when I have $scope.obj = { name : 'test' }; in MainCtrl the two-way binding is working the way I expect.

查看工作演示

<body ng-controller="MainCtrl">

    {{ obj.name }}

    <dir>
      <input type="text" ng-model="obj.name" />
    </dir>

  </body>

什么是此行为的解释?

What is the explanation of this behavior?

推荐答案

有与从子范围父范围访问原始变量的问题。你有一个孩子范围,因为有 transclude:真正的创建一个新的范围

There is an issue with accessing primitive variables on the parent scope from the child scope. You have a child scope because having transclude: true creates a new scope.

您真的应该阅读这篇文章有一个深刻的理解这是怎么回事。

You really should read this article to have a deep understanding of what's going on.

从文章的亮点:

继承范围通常是简单的,你经常不
  甚至不需要知道它正在发生......直到你尝试2路数据绑定
  (即表单元素,NG-模型)为原始(例如,数字,字符串,
  定义布尔)父范围从孩子域内。

Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope.

这与原语的问题可以按照很容易地避免
  最佳实践始终有一个'。在NG-车型。

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models.

什么情况是,当涉及到原语父范围不协商。它是JavaScript的事情,甚至没有角的。

What happens is that the parent scope is not consulted when it comes to primitives. It's a Javascript thing, not even Angular's.

我也创建了一个演示对象从孩子躲在范围。 (阴影非基本对象):

I've also created a Demo of object hiding from child scope. (shadowing a non-primitive object):

app.directive('dir', function () {
    return {
        restrict: 'E',

        scope: true,
        template: "<div><input type=\"text\" ng-model=\"obj.name\" /></div>",
        link: function(scope, element, attrs) {
          scope.obj = {name : "newname"}; 
        }

    };
});

这篇关于AngularJS - 指令以纳克-transclude,无双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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