Javascript 如何与父范围共享子指令中的数据?
我编辑了这个问题以简化它 如何与祖父母的作用域共享子指令中的数据 我想将数据放入myData属性 视图:Javascript 如何与父范围共享子指令中的数据?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我编辑了这个问题以简化它 如何与祖父母的作用域共享子指令中的数据 我想将数据放入myData属性 视图: myData={{myData | json}} 代码: var myApp=angular.module('myApp',[]); myApp.directive('generator',function(){ 返回{ 限制:'E', 范围:{ 结果:'=ngModel' }, 模板:“结果:{results | json}}” } }); myApp.controller('gene
myData={{myData | json}}
代码:
var myApp=angular.module('myApp',[]);
myApp.directive('generator',function(){
返回{
限制:'E',
范围:{
结果:'=ngModel'
},
模板:“结果:{results | json}}”
}
});
myApp.controller('generatorController',['$scope',函数($scope){
$scope.fields={fieldA:“A”,fieldB:“B”,fieldC:“C”};
$scope.results={};
}]);
myApp.directive('childWidget',function(){
返回{
限制:'E',
范围:{
fieldName:“@fieldName”,
ngModel:“=”
},
模板:“{fieldName}}:”
}
});
使用指令控制器而不是在模板内创建
ng控制器
这是一个
- 您在父范围和生成器范围之间进行了双向绑定
- 您在控制器范围和小部件范围之间进行了双向绑定
- 但是生成器作用域和控制器作用域之间没有双向绑定
太棒了,真管用!为什么它没有以另一种方式工作呢?非常感谢你,这让我觉得很多事情都很顺心!
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" />'
}
});
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}}'
}
});
| parent scope
| - generator scope <====| no data
| --- controller scope <==| binding
| ----- widget scope
| parent scope
| - generator scope ( same as the controller's scope )
| --- widget scope