在Angular1.5 +中,如何导入和使用独立组件?

时间:2017-01-11 03:54:30

标签: angularjs

现在,我在一个文件夹中写了一个Angular1.5 +组件。

独立文件夹中的组件。

我的问题是如何在不同的HTML中使用此组件。换句话说,我想找到一种方法来在两个以上的HTML文件中导入这个组件。

enter image description here

cellComponent.js是这样的:

function courseCellComponentFun() {
    var ctrl = this;
}

angular.module(app_name).component('courseCell', {
    templateUrl: '../cellComponent.html',
    controller:courseCellComponentFun,
    bindings:{
        cellData:'='
    }
})

cellComponent.html是这样的:

<div class="course_cell">
    <div class="img_box">
        <div ng-bind="$ctrl.cellData.name"></div>
    </div>
</div>

像这样的index.html:

   <body ng-app="app" ng-controller="controller">
<ul>
    <li ng-repeat="item in array1">
        <course-cell cell-data="item"></course-cell>
    </li>
</ul>
</body>
<script src="angular.js"></script>
<script>
    var app = angular.module('app',[]);
    app.controller('controller', function ($scope) {
        $scope.array1 = [
            {name:'cell1'},
            {name:'cell2'},
            {name:'cell3'},
        ]
    });
</script>

如何导入index.hmtl 中的组件?我的index.html现在无效。我看不到文字。

1 个答案:

答案 0 :(得分:0)

好吧,如果你没有使用Typescript或Babel或新的ES6标准来导入和导出模块,我很担心你必须添加component.js文件的引用,就像{一样简单} index.html

中的{1}}

<强>的index.html

<html>
<head>
    <script src="angular.js"></script>
    <script src="cellComponent.js"></script>
    <script src="appModule.js"></script>
</head>
<body ng-app="app" ng-controller="controller">
   <ul>
       <li ng-repeat="item in array1">
           <course-cell cell-data="item"></course-cell>
       </li>
   </ul>
</body>
</html>

<强> appModule.js

var app = angular.module('app',[]);
app.controller('controller', function ($scope) {
    $scope.array1 = [
        {name:'cell1'},
        {name:'cell2'},
        {name:'cell3'},
    ];
})
.component("courseCell", componentOpts); // componentOpts comes from the componentOpts.js script

<强> cellComponent.html

<div class="course_cell">
    <div class="img_box">
       <div ng-bind="$ctrl.cellData.name"></div>
    </div>
</div>

<强> cellComponent.js

function courseCellComponent() {
    var ctrl = this;
}

var componentOpts = {
    templateUrl: './cellComponent.html',
    controller: courseCellComponent,
    controllerAs: "$ctrl",
    bindings: {
        cellData:'=',
    }
};

请参阅此plunkr