具有angularJS组件的组件控制器中$ element和$ attrs的用途1.5

问题描述 投票:23回答:2

我正在努力提高1.5角度组件的速度。我一直在关注托德Motto的视频,以获得组件以及angular的文档https://docs.angularjs.org/guide/component

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

$ element,$ attrs在组件控制器内的目的是什么?这些似乎可用于操纵。这是文档中关于plunker的链接。我知道他们没有使用$元素,但这是我正在阅读的例子。 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的用途是什么?

angularjs dom angularjs-components
2个回答
21
投票

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

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

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

所以Component只不过是作为新实体创建的简单指令:

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

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


20
投票

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>

© www.soinside.com 2019 - 2024. All rights reserved.