javascript - 与 Angular Directive(指令) Controller 的两种方式数据绑定(bind)

标签 javascript angularjs data-binding angularjs-directive

Angular 允许您使用指令的范围设置双向数据绑定(bind)。有谁知道使用指令 Controller 设置双向数据绑定(bind)的简单方法。

例如:http://plnkr.co/edit/TIxXrvYpP0na4xEeYLgS?p=preview

HTML

<body ng-app="myApp" ng-controller="MyCtrl as ctrl">
  Controller Test: {{ctrl.test}}
  <div dir test="ctrl.test"></div>
</body>

JS

var MyCtrl = function($timeout) {
  this.test = {msg: 'hello'};
  var _this = this;

  $timeout(function() {
    _this.test = {msg: 'good bye'};
  }, 1000);
}

angular.module('myApp', []).directive('dir', function() {
  return {
    scope: {
      test: '='
    },
    template: '\
      <div>Directive Scope Test: {{test}}</div>\
      <div>Directive Controller Test: {{dCtrl.test}}</div>',
    controller: function($scope) {
      this.test = $scope.test;
    },
    controllerAs: 'dCtrl'
  }
});

在上面的示例中,MyCtrltest 变量绑定(bind)到 dir 指令的范围。但是,当变量被分配给指令的 Controller (this.test = $scope.test;) 时,双向绑定(bind)就被破坏了。

我将范围变量分配给 Controller 只是因为我发现在使用“controller as”语法时在使用范围变量和 Controller 变量之间来回有点尴尬。然而,我能想到的最好的解决方案是直接从 $scope 访问变量。有谁有更适合“ Controller 作为”风格 Controller 的解决方案。

最佳答案

在我看来,当您使用 Angular 1.2.* 时,这是唯一的方法,但在您的具体情况下,您实际上在指令 Controller 实例中持有旧引用(因为在您的 Controller 中,您正在覆盖由test 属性完全通过执行 _this.test = {msg: 'good bye'}; ),而您的指令 Controller 实例保留旧的(因此不会反射(reflect)更改)。

相反,如果你这样做 _this.test.msg = 'good bye';您将看到反射(reflect)的更改,因为在这种情况下您没有覆盖对象引用。 <强> Plnkr

没有自动方法将 2 路绑定(bind)范围属性附加到 Controller 实例,除非您通过监视或使用一些可以帮助您完成此操作的语法糖来处理它。

如果您将其升级到 1.3 rc,您将拥有一个属性 bindToController:true 您可以设置它,以便属性将自动附加到 Controller 实例,而不是直接附加到范围。好吧,最终 Controller 别名会附加到作用域。

<强> Plnkr

关于javascript - 与 Angular Directive(指令) Controller 的两种方式数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26006346/

相关文章:

javascript - javascript for 循环中的 DispatchEvent

javascript - 在 Rails 应用程序的移动尺寸屏幕中将图像导航元素对齐为 2 行

javascript - 我是否正确使用了 promise ?

javascript - 对 Angular 指令进行单元测试

WPF 动态设置 CellTemplate 和绑定(bind)

javascript - 显示到页面后如何编辑和删除json

javascript - 如何在单击更改按钮时更改表单?

javascript - 将 $scope.variable 从一个 View 传递到另一个 View

html - 在 Angular 组件模板中使用 'this' 关键字

DataTemplate 中的 WPF 命令绑定(bind)