[AngularJS - thoughtram] Exploring Angular 1.3: Binding to Directive Controllers

本文详细介绍了AngularJS中bindToController的作用及其实现方式。从1.2版本的复杂实现到1.3版本的简化过程,展示了如何利用此特性进行更高效的双向数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The post we have: http://www.cnblogs.com/Answer1215/p/4185504.html gives a breif introduce about bindToController on the directive.

Here is a blog about bindToController from thoughtram which explains in detail why bingToController comes into handy and why controllerAs syntax is important.

 

Here is the part which useful to myself

This is a directive with an isolated scope that defines how its scope properties are bound. Alright, let’s say we have directive with an isolated scope, a controller and a template that uses the controller properties accordingly:

app.directive('someDirective', function () {
  return {
    scope: {},
    controller: function () {
      this.name = 'Pascal'
    },
    controllerAs: 'ctrl',
    template: '<div>{{ctrl.name}}</div>'
  };
});

 

Easy. That works and we knew that already. Now to the tricky part: what ifname should be two-way bound?

 

app.directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    // ...
  };
});

 

Changes to isolated scope properties from the outside world are not reflected back to the controllers’ this object. What we need to do to make this work in 1.2, is to use the $scope service to re-assign our scope values explicitly, whenever a change happens on a particular property. And of course, we mustn’t forget to bind our watch callback to the controllers’ this:

 

app.directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    controller: function ($scope) {
      this.name = 'Pascal';

      $scope.$watch('name', function (newValue) {
        this.name = newValue;
      }.bind(this));
    },
    // ...
  };
});

 

Here we go… the $scope service we initially got rid off is now back. If you now think this is crazy, especially when considering that this is just one scope property and in a real world directive you usually have more than one, then my friend, I agree with you.

Luckily, this is no longer a problem in Angular 1.3!

 

app.directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    controller: function () {
      this.name = 'Pascal';
    },
    controllerAs: 'ctrl',
    bindToController: true,
    template: '<div>{{ctrl.name}}</div>'
  };
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值