【问题标题】:Angular JS Dynamic Template pass variableAngular JS动态模板传递变量
【发布时间】:2017-11-18 18:08:33
【问题描述】:

我有一个想要传递变量的组件。

基本上我的组件被调用:

<profileimage></profileimage>

我想通过它传递一个 ID

<profileimage userid="user.ID"></profileimage>

然后我可以在控制器中使用该 ID 来加载图像

function ProfileImageController($scope) {
   var ctrl = this;
} 
var app = angular.module('creatif')
    .component('profileimage', {
       templateUrl: 'components/profileimage/profileimage.html',
       controller: ProfileImageController
   });

【问题讨论】:

  • 什么阻止了你?
  • @31piy 我不确定如何访问用户 ID?
  • 在问题中包含组件的定义。
  • @31piy 更新了描述

标签: angularjs angularjs-directive angularjs-components


【解决方案1】:

使用bindings 接收自定义组件中的变量。

.component('profileimage', {
   templateUrl: 'components/profileimage/profileimage.html',
   controller: ProfileImageController,
   bindings: {
     userid: '<'
   }
});

然后您可以通过this.userid 在您的控制器中使用userid。通过angular's documentation 了解更多信息。

奖励提示

将指令定义移出控制器函数。

function ProfileImageController($scope) {
   var ctrl = this;
}

angular.module('creatif')
  .component('profileimage', {
     templateUrl: 'components/profileimage/profileimage.html',
     controller: ProfileImageController,
     bindings: {
       userid: '<'
     }
  });

看起来更具可读性,不是吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2020-02-11
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2015-09-30
    • 2020-09-27
    相关资源
    最近更新 更多