AngularJs 1.7 es6组件内的数据在模板文件中不可用

时间:2018-05-20 16:55:52

标签: javascript angularjs webpack

我只是在组件和模块设置上创建项目AngularJs 1.7和webpack 4以及ES6类。

这是我的app主模块。

// Core Styles
import './styles/main.scss';

// Core Angular
import angular from 'angular';

import { AppComponent } from "./app.component";
import CommonModule from './modules/common/common.module';
import PackagesModule from './modules/packages/packages.module';
import PackagesService from "./services/packages.service";

// These all export the module name
// import ngAnimateModuleName from 'angular-animate';

const dependencies = [
    // ngAnimateModuleName
    CommonModule.name,
    PackagesModule.name
];

angular.module('app', dependencies)
    .component('appComponent', AppComponent)
    .service('PackagesService', ['$http', PackagesService]);

这是我的js组件文件。

import './app.component.scss';

export const AppComponent = {
    template: require('./app.component.html'),
    controller: [
        'PackagesService',
        class AppController {
            constructor (PackagesService) {
                this.test = 11;
            }
    }]
};

但似乎test变量在模板文件中不可用。

<header-component></header-component>

<div class="container">
    <div class="row">
        <div class="col-6">
            <div class="packages-name-box">
                <h1 class="homepage-title">Packages Name {{ test }}</h1>
                <packages-list-group pages-data="pagesPackageData"></packages-list-group>
            </div>
        </div>
    </div>
</div>

enter image description here

这是webpack.confing中的HTML LOADER

{
    // HTML LOADER
    // Reference: https://github.com/webpack/raw-loader
    // Allow loading html through js
    test: /\.html$/,
    loader: 'raw-loader'
}

我错过了为什么this.test没有在模板中显示任何内容的东西?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

由于您未使用ControllerAs语法,因此应将值分配给$ scope变量

$scope.test = 11;

你需要注入$ scope

 'PackagesService','$scope',
        class AppController {
            constructor (PackagesService,$scope) {
                 $scope.test = 11;
            }

答案 1 :(得分:0)

On angularjs components, all variables declared with this can be acessed by the object $ctrl on the scope. You should use:

<h1 class="homepage-title">Packages Name {{ $ctrl.test }}</h1>

you can change the object name to whatever you want on controllerAs like this: (but it's $ctrl by default)

export const AppComponent = {
template: require('./app.component.html'),
controllerAs: 'vm',
controller: [
    'PackagesService',
    class AppController {
        constructor (PackagesService) {
            this.test = 11;
        }
}]
};

see angularjs component document: https://docs.angularjs.org/guide/component