AngularJS组件:使用= binding

时间:2016-12-04 04:01:35

标签: angularjs

我正在尝试将参数传递给AngularJS组件(Angular 1.5)。但是,我无法在组件中访问它们。谁能告诉我代码有什么问题?

http://jsbin.com/fopuxizetu/edit?html,js,output

1 个答案:

答案 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>