【问题标题】:Angular js - Binding to functionAngular js - 绑定到函数
【发布时间】:2018-04-18 20:09:16
【问题描述】:

我已经绑定到看起来像这样的函数:

function func() {
    this.scopeVar = {
        bla: this.isolateScopeVar.bla,
        gla: this.isolateScopeVar.gla
    }
}

我有这个 html 代码:

<span>{{this.scopeVar.bla}}</span>
<span>{{this.scopeVar.gla}}</span>

我的问题是,如果 this.isolateScopeVar.blathis.isolateScopeVar.gla 已更改,span 不会在没有任何 func 触发的情况下更新。

我可以使用这个可行的方法:

function func() {
    return {
        bla: this.isolateScopeVar.bla,
        gla: this.isolateScopeVar.gla
    }
}

<span>{{this.func().bla}}</span>
<span>{{this.func().gla}}</span>

但我认为这不是最好的方法。

还有其他正确的方法吗?

【问题讨论】:

  • 为什么要通过一个函数来获取这些值? this.isolateScopeVar.bla 不工作?
  • ^ 或者如果你有 this. 使用什么语法?

标签: javascript html angularjs data-binding


【解决方案1】:

这是可能的。这是一个例子:

angular.module('app', [])
.component('appComponent', {
      template: [
        '<span>{{ $ctrl.getData().bla }}</span><br>',
        '<span>{{ $ctrl.getData().gla }}</span>',
      ].join(''),

      controller: function () {

        this.getData = function(){

          var isolateScopeVar = {}
          isolateScopeVar.bla = 'my item bla'
          isolateScopeVar.gla = 'my item gla'

          return {
              bla: isolateScopeVar.bla,
              gla: isolateScopeVar.gla
          }
        }
      }
});

现场演示是here

【讨论】:

    【解决方案2】:

    让我们开始吧,我希望您使用的是 Angular 的最新版本,可能是 components,它具有孤立的范围。

    在模板中,您可以使用$ctrl 访问控制器。

    <span>{{$ctrl.bla}}</span>
    

    bla 在控制器声明中定义:

    angular.module('whatever').controller('theNameController', {
        bindings: {
            bla: '<' // if you want this to be settable from who's using the component
        },
        controller: () => {
            bla = 42; // or declare it here if you want it be completely isolated
        },
        require: { },
        templateUrl: 'myTemplate.html'
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 2023-03-18
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      相关资源
      最近更新 更多