我有一个非常大的标记,由ng-controller
包裹,看起来像这样:
<div ng-controller="MyController">
<script>
// MyController is bootstraped with current_item_data to save additional work of loading data using service, etc.
var current_item_data = <?= json_encode($this->view->current_item_data) ?>;
var current_parent_item_data = <?= json_encode($this->view->current_parent_item_data) ?>;
</script>
<!-- large markup comes here -->
</div>
现在,问题是我想在同一页面中多次重复使用该控制器,例如:
<div>
<!-- * included by php template engine -->
<div ng-controller="MyController">
<script>
var current_item_data = []; /* holds item #1 data */
var current_parent_item_data = []; /* holds parent item #1 data */
</script>
</div>
<!-- /included template -->
<!-- * included by php template engine -->
<div ng-controller="MyController">
<script>
var current_item_data = []; /* holds item #2 data */
var current_parent_item_data = []; /* holds parent item #2 data */
</script>
</div>
<!-- /included template -->
</div>
在MyController
初始化逻辑中,我有:
app.controller('MyController', ['$scope', '$window', function($scope, $window) {
$scope.currentItemData = $window.current_item_data;
$scope.parentItemData = $window.current_parent_item_data;
}]);
我认为你在这里看到了问题,每次实例化MyController
时,它都使用相同的全局变量,并且它没有按预期工作。
是的,我正在寻找任何解决方法,因为我现在无法重构代码库。
答案 0 :(得分:1)
您的模板中不应包含<script>
个标签。相反,您可以使用angular ng-init
指令:
<div ng-controller="MyController"
ng-init="init(<?= json_encode($this->view->current_item_data) ?>, <?= json_encode($this->view->current_parent_item_data) ?>)">
</div>
在你的控制器中:
app.controller('MyController', ['$scope', '$window', function($scope, $window) {
$scope.currentItemData = [];
$scope.parentItemData = [];
$scope.init = function(currentItemData, parentItemData) {
$scope.currentItemData = currentItemData;
$scope.parentItemData = parentItemData;
}
}]);
答案 1 :(得分:0)
或者您可以使用routeProvider ..您可以根据页面分配控制器。希望这会有所帮助..
DEMO 此处
<强> app.js 强>
var app = angular.module('myModule', ["ngRoute"]);
app.config(function($routeProvider) {
// set up routing
$routeProvider.when('/', {
templateUrl : 'templates/dashboard.html',
controller : 'mainCtrl',
title : 'Home'
}).when('/about', {
templateUrl : 'templates/about.html',
controller : 'AboutController',
title : 'About'
}).when('/contact', {
templateUrl : 'templates/contact.html',
controller : 'ContactController',
title : 'Contact'
}).otherwise({
redirectTo : '/'
});
});
<强> HTML 强>
<!DOCTYPE html>
<html lang="en" ng-app="myModule">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AD Operation Reports</title>
</head>
<body >
<div ng-view></div>
</body>
</html>