问题描述
我应该给我的指令什么范围,以便输入显示初始值 "Toto" ?我不想采取范围:true
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 代码:
<!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代码:
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
Plunker here: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 元素都与一个且唯一关联一个范围.
这意味着我们不能让给定元素的属性子集与一个作用域和另一个具有不同作用域的子集一起使用.这正是您在 plunker 中尝试做的事情,您希望 ng-model
属性在一个范围内工作(在 元素上定义的那个范围)通过
ng-controller
指令)和具有另一个作用域的 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-model="$parent.value.name"
明确地将 ng-model 指令指向某个范围.但这很脆弱而且不明显.
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-model
结合使用).您仍然可以使用 $parse
服务获取属性的值.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!