我已编辑此问题以简化
如何与祖父母的范围共享子指令中的数据?
我想将数据导入myData属性
视图:
<generator ng-model="myData"></generator>
myData={{myData|json}}
代码:
var myApp = angular.module('myApp', []);
myApp.directive('generator', function() {
return {
restrict: 'E',
scope: {
results: '=ngModel'
},
template: '<div ng-controller="generatorController"><div ng-repeat="field in fields"><child-widget field-name="{{field}}" ng-model="results[field]"></child-widget></div>results:{{results|json}}</div>'
}
});
myApp.controller('generatorController', ['$scope', function ($scope) {
$scope.fields = { fieldA: "A", fieldB: "B", fieldC: "C" };
$scope.results = {};
}]);
myApp.directive('childWidget', function () {
return {
restrict: 'E',
scope: {
fieldName: '@fieldName',
ngModel: '='
},
template: '{{fieldName}}: <input type="text" ng-model="ngModel" />'
}
});
答案 0 :(得分:1)
使用指令控制器,而不是在模板中创建ng-controller
这是一个plunker
myApp.directive('generator', function() {
return {
restrict: 'E',
scope: {
results: '=ngModel'
},
controller: 'generatorController',
template: '<div ng-repeat="field in fields">' +
'<child-widget field-name="{{field}}" ng-model="results[field]"></child-widget>' +
'</div>results:{{results|json}}'
}
});
ng-controller
? ng-controller
始终会创建一个新的(非隔离的)范围。
所以这就是范围树在你的例子中的样子:
| parent scope
| - generator scope <====| no data
| --- controller scope <==| binding
| ----- widget scope
在我的示例中,只有3个范围,因此它可以工作:
| parent scope | - generator scope ( same as the controller's scope ) | --- widget scope