【问题标题】:change controller property from another controller从另一个控制器更改控制器属性
【发布时间】:2016-07-18 10:50:12
【问题描述】:

我有一个应用程序,它有一个导航栏,我已将它放在“应用程序”上下文中。默认情况下,这些导航栏链接将被禁用,并且只会在模板中的特定操作上启用。

应用程序控制器包含导航栏中链接的禁用状态:-

App.ApplicationController = Ember.Controller.extend({
userName:"TestUser",
firstLinkDisabled:true,
actions:{
    handleToggle:function(){
        console.log("Handling application action with linkstatus="+this.firstLinkDisabled);
        //this.set("firstLinkDisabled",false);
        this.toggleProperty("firstLinkDisabled");
    }
}

})

索引控制器会将操作发送到应用程序控制器:-

App.IndexController = Ember.Controller.extend({
actions:{
    toggleApplicationButton:function(){
        this.controllerFor("Application").send("handleToggle");
    }
}

})

应用模板:

【问题讨论】:

  • 即使在使用 Ember.inject.controller() 之后问题也是一样的。我可以在控制台中看到变量的变化。但在 Ember 检查器中,变量保持不变 并且链接仍然被禁用。这是 Ember 中的错误吗?

标签: ember.js


【解决方案1】:

这是我项目中的一个简单示例:

import Ember from 'ember';

export default Ember.Controller.extend({
  /*first, inject a controller*/
  loginController: Ember.inject.controller('lang.login'),
  /*some code*/

  actions: {
    register: function () {
      /*some code*/
      /*work with injected controller*/
      var c = this.get('loginController');
      c.set('identification', that.get('user').email);
      c.set('password', that.get('user').plainPassword);
      /*some code*/
    }
  }
});

ember docs

【讨论】:

    【解决方案2】:

    使用Ember.inject.controller()

    App.IndexController = Ember.Controller.extend({
      appController: Ember.inject.controller("Application"),
      actions:{
        toggleApplicationButton:function(){
            this.get("appController").send('handleToggle');
        }
      }  
    })
    

    controllerFor 你可以在路由中使用

    您也可以使用alias

    appController: Ember.computed.alias('controllers.Application')
    

    详情请参考 Emberjs official documentation

    【讨论】:

      【解决方案3】:

      首先,将应用控制器注入到索引控制器中

      //index.js
      application: Ember.inject.controller(),
      

      然后您可以像这样访问应用程序控制器中的属性:

      //index.js
      application.toggleProperty("firstLinkDisabled");
      

      【讨论】:

        猜你喜欢
        • 2011-06-15
        • 2012-04-02
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 2012-04-26
        • 2015-09-07
        • 2022-08-23
        相关资源
        最近更新 更多