Heim > Fragen und Antworten > Hauptteil
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次?
phpcn_u15822017-05-15 17:07:18
能看你的路由配置和html片段页面吗?
一般情况是路由里配置了controller,在路由html片段里又声明了ng-controller。
------ 分割线 -----
很明显吗!你既在路由里配置了HomeController,又在home.html声明了ng-controller="HomeController" 当然会执行两遍啦!