与输入的范围破ngmodel指令 [英] Directive with scope breaking ngmodel of an input

查看:127
本文介绍了与输入的范围破ngmodel指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该给什么范围到我的指令,使得输入显示初始值托托?
我不想拿范围:真正的

What scope should I give to my directive so that the input displays the initial value "Toto" ? I don't want to take scope:true

HTML code:

HTML code:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
   <input customattr type = "text" ng-model="value.name" />   
</body>
</html>

JS code:

JS code :

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.value = {"name":"Toto", "id":1};

});

    app.directive('customattr', function () {
      return {
          restrict: 'A',
          scope: {
          },
          link: function (scope, element, attrs) {

          } 
      }; 
    });

Plunker在这里:
http://plnkr.co/edit/JxWElWhTeBbNpFHS0wYT

推荐答案

我想这是人们以AngularJS指令和范围碰到经常的事情之一。要了解解决方案和建议,接下来我们需要明白一件事AngularJS DOM元素和范围:

I guess this is one of the things that people bump into quite often with AngularJS directives and scopes. To understand the solution and recommendations that follow we need to understand one thing about AngularJS DOM elements and scopes:

在AngularJS任何单一的DOM元素与一个且仅相关联
  一个作用域。

In AngularJS any single DOM element is associated with one and only one scope.

这意味着我们不能有一个给定的元素的属性的一个子集与一个范围,并用不同的范围另一子集来工作。这正是你想在你的p​​lunker,你希望 NG-模型属性有一个作用域(在定义的工作做 &LT;身体GT; NG-控制器指令元素)和 customattr 与另一范围 - 在一个指令产生的孤立的)

This means that we can't have a subset of attributes on a given element to work with one scope and another subset with a different scope. This is exactly what you are trying to do in your plunker where you expect the ng-model attribute to work with one scope (the one defined on the <body> element by the ng-controller directive) and the customattr with another scope - the isolated one created in a directive).

您已经有了基本方法摆脱这种局面:

You've got basically 2 ways out of this situation:

1)使用 NG-模式=$ parent.value.name来的NG-模型指令明确指出一定范围内。但是,这是脆,并不明显。

1) Use ng-model="$parent.value.name" to explicitly point the ng-model directive to a certain scope. But this is brittle and not obvious.

2)从属性指令删除分离的范围。根据经验我会建议反对,都应该使用的指令范围孤立的规则被用作输入字段属性的人(连同 NG-模型)。您仍然可以通过使用 $解析服务中获得的属性值。

2) Drop the isolated scope from the attribute directive. As a rule of thumb I would advice against using isolated scopes in directives that are supposed to be used as attribute ones on the input fields (in conjunction with ng-model). You can still get values of an attribute by using the $parse service.

这篇关于与输入的范围破ngmodel指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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