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

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>'
  };
});
复制代码

 

posted @   Zhentiw  阅读(229)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示