27

我正在努力加快使用 1.5 个角度分量的速度。我一直在关注 todd Motto 的视频,以了解组件以及 Angular 的文档 https://docs.angularjs.org/guide/component

在这一点上,组件似乎正在取代使用控制器的指令,但在我们的 1.5 代码中,我们仍然会使用指令来进行 dom 操作。

$element, $attrs 在组件控制器中的用途是什么?这些似乎可用于操纵。这是文档中 plunker 的链接。我知道他们没有使用 $element,但这是我正在阅读的示例。http://plnkr.co/edit/Ycjh1mb2IUuUAK4arUxe?p=preview

但是在这样的代码中......

 angular
  .module('app', [])
  .component('parentComponent', {
    transclude: true,
    template: `
      <div ng-transclude></div>
    `,
    controller: function () {
      this.foo = function () {
        return 'Foo from parent!';
      };
      this.statement = function() {
        return "Little comes from this code";
      }
    }
  })
  .component('childComponent', {
    require: {
      parent: '^parentComponent'
    },
    controller: function () {

      this.$onInit = function () {
        this.state = this.parent.foo();
        this.notice = this.parent.statement();
      };
    },
    template: `
      <div>
        Component! {{ $ctrl.state }}
        More component {{$ctrl.notice}}
      </div>
    `
  })

如果我们不操作 dom,那么 $element 有什么用?

4

2 回答 2

24

这是一个很好的问题。我有一个简单的答案。

它们发生在组件中只是因为Component 是指令的语法糖

在 Angular 添加组件之前,我对指令使用了某种组件语法,这就像一个约定,在我们的项目中,我们有两种指令,一种负责 DOM 操作,第二种是带有模板的指令,不应该操作DOM。添加组件后,我们只是更改了名称。

因此Component,无非是作为新实体创建的简单指令,它:

  1. 总是有模板
  2. 范围始终是孤立的
  3. 限制总是元素

我认为您可以在角度源中找到更多答案,但我建议您不要混合这些实体,如果您需要在组件内部操作 DOM,只需在内部使用指令即可。

于 2016-09-19T05:18:22.097 回答
22

Angular 组件生命周期钩子允许我们使用 $element 服务在组件控制器内部进行 DOM 操作

var myApp = angular.module('myApp');
myApp.controller('mySelectionCtrl', ['$scope','$element', MySelectionCtrl]);

myApp.component('mySection', {
    controller: 'mySelectionCtrl',
    controllerAs: 'vm',
    templateUrl:'./component/view/section.html',
    transclude : true
});

function MySelectionCtrl($scope, $element) {
    this.$postLink = function () {
        //add event listener to an element
        $element.on('click', cb);
        $element.on('keypress', cb);

        //also we can apply jqLite dom manipulation operation on element
        angular.forEach($element.find('div'), function(elem){console.log(elem)})

    };

    function cb(event) {
        console.log('Call back fn',event.target);
    }
}

在 html 中声明组件

<my-section>
<div class="div1">
    div 1
    <div>
        div 1.1
    </div>
</div>
<div class="div2">
    div 1
</div>

组件的部分模板(./component/view/section.html)

<div>
<div class="section-class1">
    div section 1
    <div>
        div section 1.1
    </div>
</div>
<div class="section-class1">
    div section 1
</div>

于 2017-03-15T18:09:28.930 回答