下面是一个使用AngularJS创建子组件的示例代码:
首先,我们需要在HTML页面中引入AngularJS库:
然后,在JavaScript代码中定义一个父组件和一个子组件:
// 定义父组件
app.controller('ParentController', function($scope) {
$scope.message = "Hello from parent component!";
});
// 定义子组件
app.component('childComponent', {
bindings: {
message: '<' // 通过绑定属性接收父组件传递的消息
},
template: '{{ $ctrl.message }}
'
});
在HTML页面中使用父组件和子组件:
在上面的示例中,父组件通过$scope.message
定义了一个消息,并将其传递给子组件通过message
属性。子组件通过bindings
属性接收父组件传递的消息,并在模板中显示出来。
当你运行这个示例时,你将看到子组件显示父组件传递的消息:“Hello from parent component!”