角度范围,神秘?

时间:2016-10-28 16:50:32

标签: javascript angularjs scope

我有两个指令,隔离共享隔离指令直接将双向绑定传递给共享< / strong>指令但共享指令未使用隔离范围,正在创建自己的。

目标是当共享指令更改时,隔离指令应响应双向绑定中的更改。

<body ng-app="app">
  <div ng-controller="main as $ctrl">
    <h3>Main data: {{$ctrl.data.bind}}</h3>
    <isolated bind="$ctrl.data.bind"></isolated>
  </div>
</body>

angular.module("app", [])
.controller("main", function() {
  this.data = {
    bind: 123
  }
})
.directive("isolated", function() {
return {
  scope: {
    bind: '='
  },
  bindToController: true,
  template: '<div><h3>Parent directive data: {{$ctrl.bind}}</h3> </div>'
            + '<input type="text" shared ng-model="$ctrl.bind" />',
  controller: function() {
    this.changed = function() {
      console.log('Data changed: ' + this.bind);
    }
  },
  controllerAs: '$ctrl',
  link: {
    pre: function($scope) {
      console.log("Parent data: " + $scope.$ctrl.bind);
    }
  }
}
})
.directive("shared", function() {
  return {
    restrict: 'A',
    require: {
      ngModel: '^'
    },
    bindToController: true,
    link: function($scope) {
      console.log('Current data in shared: ' + $scope.$ctrl.bind)
    },
    controller: function() {
      this.$postLink = function() {
        this.ngModel.$modelValue = 321;
      }
    },
    controllerAs: '$ctrl'
  }
});

我有一个Plunker

1 个答案:

答案 0 :(得分:0)

Gourav Garg是对的。由于共享范围,第二个指令声明将覆盖$scope.$ctrl字段。无论如何,第二个声明中的controllerAs属性是不需要的,因为您永远不会访问模板中的控制器属性。如果您最终需要在模板中使用第二个指令控制器信息,则需要将其声明为$ctrl之外的其他名称,或者更好的是,使用require语法来要求关于第一个指令的第二个指令。这会将第二个指令的控制器绑定到第一个指令控制器上的属性。

有关require的更多信息,请参阅&#34;创建通信指令&#34;角度指令指南here的一部分。

祝你好运!