Win*_*cca 24 dom angularjs angularjs-components
我正在努力提高1.5角度组件的速度.我一直在关注Todd 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>
`
})
Run Code Online (Sandbox Code Playgroud)
如果我们不操纵dom,$ element的用途是什么?
Mik*_*kki 21
这是一个很好的问题.我有一个简单的答案.
它们发生在组件中只是因为Component是指令的语法糖.
在角度添加组件之前,我使用某种组件语法作为指令,它就像一个约定,在我们的项目中我们必须使用各种指令,一个负责DOM操作,第二个是带有模板的指令,不应该操作DOM.添加组件后,我们只更改了名称.
所以Component只不过是作为新实体创建的简单指令:
我认为你可以在角度来源中找到更多的答案,但我建议你不要混合这些实体,如果你需要在你的组件内部操作DOM,只需在里面使用指令.
Rat*_*esh 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在html中声明组件
<my-section>
<div class="div1">
div 1
<div>
div 1.1
</div>
</div>
<div class="div2">
div 1
</div>
Run Code Online (Sandbox Code Playgroud)
组件的部分模板(./ 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31066 次 |
| 最近记录: |