我有嵌套指令。
我从第一个发送数据,第二个发送数据。
问题是我失去了与主范围的绑定。
这是我的代码: Plunker
(单击按钮会更改主范围内的值,但不会更改指令中的值)
angular.module('app', [])
.controller('MainCtrl', function($scope) {
$scope.change = function(){
var id = Math.floor((Math.random() * 4) + 0);
var val = Math.floor((Math.random() * 100) + 1);
$scope.data.items[id].id = val;
}
$scope.data = {
items: [{
id: 1,
name: "first"
}, {
id: 2,
name: "second"
}, {
id: 3,
name: "third"
}, {
id: 4,
name: "forth"
}]
}
})
.directive('firstDirective', function($compile) {
return {
replace: true,
restrict: 'A',
scope: {
data: '='
},
link: function(scope, element, attrs) {
var template = '';
angular.forEach(scope.data, function(item, key) {
var sss = JSON.stringify(item).replace(/"/g, "'");
var tmp = '<div>' +
'<div second-directive data="' + sss + '"></div>' +
'</div>';
template = template + tmp;
});
element.html(template);
$compile(element.contents())(scope);
}
}
})
.directive('secondDirective', function() {
var comp = function(element, attrs){
var data = JSON.parse(attrs.data.replace(/'/g, "\""));
var template = '<div class="second-directive">' +
'<h4>Directive 2</h4>' +
'ID :' + data.id + '<br />' +
'Name : ' + data.name +
'</div>';
element.replaceWith(template);
}
return {
replace: true,
restrict: 'A',
compile: comp
};
});
/* Put your css in here */
.second-directive{
border:1px solid green;
padding:4px;
text-align:center;
width:100px;
height:auto;
overflow:hidden;
float:left;
margin:2px;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>MainCtrl</h2>
{{data}}
<BR />
<button ng-click="change()">change value</button>
<div first-directive data="data.items">
</div>
</body>
</html>
非常感谢
阿维