찾다

 >  Q&A  >  본문

angular.js - angular + es6 + webpack遇到的问题?

1、代码如下:

//app.js

import angular from "angular";
import uiRouter from "angular-ui-router";
import routing from "./app.config";
import HomeController from "./controllers/home.controller";

let app = angular.module('app', [uiRouter]);
app.config(routing)
    .controller('HomeController', HomeController)

2、home.controller.js代码如下:

class HomeController{
    constructor($scope){
        console.info('为什么这里运行了两次?');
    }
}

HomeController.$inject = ['$scope'];

export default HomeController;

3、app.config.js代码如下:

routing.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider'];

export default function routing($stateProvider, $urlRouterProvider, $locationProvider){
    $urlRouterProvider.otherwise('/home');

    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: require('../views/home.html'),
            controller: 'HomeController',
            title: '社区综合受理平台'
        })
        .state('record', {
            url: '/record',
            templateUrl: 'views/record.html',
            controller: 'RecordController',
            title: '社区服务综合受理记录'
        })
        .state('guide', {
            url: '/guide',
            templateUrl: 'views/guide.html',
            title: '社区受理服务事项'
        })
        .state('proof', {
            url: '/proof',
            templateUrl: 'views/proof.html',
            controller: 'ProofController',
            title: '居住证明'
        })
        .state('poor', {
            url: '/poor',
            templateUrl: 'views/poor.html',
            controller: 'PoorController',
            title: '就业困难人员待定'
        })
};

4、html如下:

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title ng-bind="title"></title>
</head>
<body ng-controller="MainController" ui-view>
</body>
</html>

5、home.html:

<p id="root">
    <p class="head clearfix">
        <ul class="title clearfix">
            <li>
                <h3 ng-bind="title"></h3>
            </li>
        </ul>
    </p>
    <p class="content">
        <p class="content-wrap clearfix index-content" ng-controller="HomeController">
            这个是模板!!!
        </p>
    </p>
</p>

6、问题:为什么constrcutor()运行了2次?

高洛峰高洛峰2744일 전635

모든 응답(1)나는 대답할 것이다

  • phpcn_u1582

    phpcn_u15822017-05-15 17:07:18

    라우팅 구성 및 html 조각 페이지를 볼 수 있나요?
    일반적으로 컨트롤러는 라우팅에 구성되고 ng-controller는 라우팅 html 조각에 선언됩니다.

    ------선 구분------
    당연하지 않나요! 경로에 HomeController를 구성하고 home.html에 ng-controller="HomeController"를 선언했습니다. 물론 두 번 실행됩니다!

    회신하다
    0
  • 취소회신하다