通用AngularJS组件

时间:2017-08-30 12:25:30

标签: angularjs angularjs-directive angularjs-scope angularjs-components

我正在尝试创建一个通用组件来显示变量,并可能从其范围调用方法。

编写<component config-name></component>感觉非常自然,因此我不得不考虑使用属性指令中的变量填充通用组件的范围。

该指令将提供显示变量,调用方法等

我最终得到了类似的东西:

var app = angular.module('app', []);

app.component('component', {
  template: '<li>{{data}}</li>'
});

app.directive('dirA', function() {
  return {
    restrict: 'A',
    controller: function($scope) {
      $scope.data = 'First directive!';
    }
  };
});

app.directive('dirB', function() {
  return {
    restrict: 'A',
    controller: function($scope) {
      $scope.data = 'Second directive!';
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>

<h2>Expectations</h2>
<ul>
  <li>First directive!</li>
  <li>Second directive!</li>
</ul>

<h2>Reality</h2>
<ul ng-app="app">
  <component dir-a></component>
  <component dir-b></component>
</ul>

但是,组件的范围保持为空。我怎样才能使指令填充其组件元素的范围?

这甚至是AngularJS的做事方式吗?如果不是,那么做类似事情的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

你做错了,一个组件更像是一个指令,但也像一个以angular 1.5开头的指令的替代品。

注意:组件只是指令的改进版本,因此您不能将指令作为属性传递给组件。要将值传递给组件,请使用绑定:

angular.module('myApp')
    .component('component', {
        templateUrl: 'component.html',
        controller: function ComponentCtrl(){
            this.innerProp = "inner";  //Tied to controller scope
        },
        controllerAs: 'vm',   // Replaces scope, by default components use `$ctrl`
        bindings: {
           input: '=?'
        }
});

component.html中你可以这样做:

<div>
    {{vm.innerProp}} /*Scope variable from controller*/
    {{vm.input}} /*Attribute from bindings*/
</div>

在父组件/模板中,您可以这样做:

<component input="someModel"></component>

传递给父模板中输入的值将传递给component.html并替换vm.input