我应该给我的指令什么范围,以便输入显示初始值"Toto" ?我不想使用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) {
}
};
});
恰好在这里:http://plnkr.co/edit/JxWElWhTeBbNpFHS0wYT
我想这是人们在使用AngularJS指令和作用域时经常遇到的事情之一。为了理解下面的解决方案和建议,我们需要了解关于AngularJS DOM元素和作用域的一件事:
在AngularJS中,任何一个DOM元素都只与一个元素关联一个范围。
这意味着我们不能让给定元素上的属性子集在一个作用域下工作,而另一个子集在不同的作用域下工作。这正是您在柱塞中试图做的事情,您期望ng-model
属性使用一个范围(由ng-controller
指令在<body>
元素上定义的范围)和customattr
使用另一个范围-在指令中创建的孤立的范围)。
你基本上有两种方法来摆脱这种情况:
1)使用ng-model="$parent.value.name"
显式地将ng-model指令指向某个作用域。但这是脆弱的,不明显的。
2)从属性指令中删除隔离的作用域。作为经验法则,我建议不要在指令中使用孤立的作用域,这些作用域应该用作输入字段的属性(与ng-model
一起使用)。您仍然可以通过使用$parse
服务获取属性的值。