Angular JS动态模板传递变量

Angular JS Dynamic Template pass variable

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

基本上我的组件被调用:

<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
   });

使用 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: '<'
     }
  });

看起来更易读,不是吗?