如何与父作用域的子指令共享数据?

时间:2014-01-20 12:35:26

标签: javascript angularjs angularjs-directive

我已编辑此问题以简化

如何与祖父母的范围共享子指令中的数据?

我想将数据导入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" />'
  }
});

http://jsfiddle.net/sbRBL/5/

1 个答案:

答案 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