如何使用新的controllerAs语法和面向对象控制器在Angular中实现双向绑定

How do I get two way binding to work in Angular with new controllerAs syntax and Object Oriented Controllers?

本文关键字:Angular 实现 绑定 控制器 面向对象 何使用 controllerAs 语法      更新时间:2023-09-26

我害怕"scope汤",人们把太多的功能挂在$scope上。因此,我正在试验面向OO的控制器,即新的控制器A,并在我的控制器中使用EC5风格的getter/setter。这很好用,但现在我想以两种方式将指令的作用域绑定到控制器的作用域,但它并没有像我预期的那样工作。我已经创建了这个代码笔来显示它。

http://codepen.io/anon/pen/DlfxB?editors=101

我希望这条线路能正常工作:

scope: { pants: '='},

如果您在1.3 rc版本中,可以使用bindToController选项,将双向绑定的范围变量绑定到控制器上。否则,您将不得不手动将属性映射到控制器实例(这很痛苦),或者只使用常规语法(没有controller.)来处理双向绑定属性。因此,您可以在指令配置中使用bindToController:true执行'<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'

bindToController
  • 当隔离作用域用于组件(见上文),并且使用controllerAs时,bindToController
  • 允许组件将其属性绑定到控制器,而不是绑定到作用域。当控制器
  • 如果实例化,则隔离作用域绑定的初始值已经可用

(function(){
    
   var myApp = angular.module('plunker', []);
    var helloEC5 = function(){
      this.pants = "jeans";
    };
    helloEC5.prototype = {
        firstName: 'Seeya',
        lastName: 'Latir',
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        },
        set fullName (name) {
            var words = name.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
        }
    };
    myApp.controller('HelloEC5', helloEC5);
    myApp.directive('myDirective', function () {
        return {
          scope: { pants: '='},
          controllerAs: 'my',
          controller: function(){},
          bindToController:true,
          template: '<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'
        }
    });
 })();
   <script data-require="angular.js@1.3.0-rc.1" data-semver="1.3.0-rc.1" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script>
  <div ng-app="plunker">
    <div ng-controller="HelloEC5 as EC5">
      <p>HelloEC5 says my name is: {{EC5.fullName}} wearing {{EC5.pants}}!</p>
      <label>Pants:</label>
      <input ng-model="EC5.pants" type="text" />
      <label>FirstName:</label>
      <input ng-model="EC5.firstName" type="text" />
      <div my-directive="" pants="EC5.pants"></div>
      <hr />
      <label>Setting HelloEC5.fullName:</label>
      <input ng-model="EC5.fullName" />
    </div>
  </div>