我正在尝试将参数传递给AngularJS组件(Angular 1.5)。但是,我无法在组件中访问它们。谁能告诉我代码有什么问题?
答案 0 :(得分:3)
在第一个代码段中,我用@
替换了绑定,以便它获取值。如果您使用=
绑定,则希望您传入变量。
在第二个代码段中,我使用了=
绑定,但使用ng-int
创建了变量。
angular
.module('client', [])
.component('testComponent', {
template: '<h1>{{$ctrl.param}}</h1>',
controller: function() {
// this.param = '123';
},
bindings: {
param: '@'
}
})
.component('heroDetail', {
template: '<span>Name: {{$ctrl.hero}}</span>',
controller: function() {},
bindings: {
hero: '@'
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS Example</title>
<!-- AngularJS -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body>
<div ng-app="client">
Test
<test-component param = "Test123"> </test-component>
<hero-detail hero="Superman"></hero-detail>
</div>
</body>
</html>
使用=绑定的代码段。
angular
.module('client', [])
.component('testComponent', {
template: '<h1>{{$ctrl.param}}</h1>',
controller: function() {
// this.param = '123';
},
bindings: {
param: '='
}
})
.component('heroDetail', {
template: '<span>Name: {{$ctrl.hero}}</span>',
controller: function() {},
bindings: {
hero: '='
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJS Example</title>
<!-- AngularJS -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body>
<div ng-app="client" ng-init="testParam= 'Test123'; testHero='Superman'">
Test
<test-component param = "testParam"> </test-component>
<hero-detail hero="testHero"></hero-detail>
</div>
</body>
</html>