我有一个控制器,我在两个地方使用:ng-view和ng-include。这些地方不是彼此的子项或父项,但我也想对ng-include的影响进行一些更改。我该怎么做?
这是这些代码部分的补充。
我想当单击"编辑用户"时,表中的user.userName显示在弹出窗口中。
索引.html
<body>
<div ng-view></div>
<div ng-include="'edit-user.html'"></div>
<script src="app.js"></script>
<script src="UsersController.js"></script>
</body>
应用.js
var app = angular.module('myApp', ['ngRoute', 'ui.materialize'])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'users.html',
controller: 'UsersController'
})
.otherwise({redirectTo: '/'});
}]);
用户.html
<h4>Users</h4>
<table class="striped highlight">
<thead>
<tr>
<th data-field="displayName">Display Name</th>
<th data-field="userName">User Name</th>
<th data-field="registered">Registered</th>
<th data-field="updated">Updated</th>
<th data-field="email">Email</th>
<th data-field="authority">Authority</th>
<th data-field="edit">Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td ng-bind="user.displayName"></td>
<td ng-bind="user.userName"></td>
<td ng-bind="user.registered"></td>
<td ng-bind="user.updated"></td>
<td ng-bind="user.email"></td>
<td ng-bind="user.authority"></td>
<td><a class="collection-item waves-effect waves-teal" modal open="openModal" ng-click="openModalFunc(user)">Edit user</a></td>
</tr>
</tbody>
</table>
<a data-target="edit-user" class="hide" modal open="openModal">Edit user</a>
用户控制器.js
app.controller('UsersController', ['$scope', function($scope) {
// create fake users
$scope.users = [
{
displayName: 'Alexander',
registered: '02-07-2017',
updated: '02-07-2017',
email: 'alex@gmail.com',
authority: 'admin',
userName: 'Alex'
},
{
displayName: 'Lev',
registered: '02-07-2017',
updated: '02-07-2017',
email: 'lev@gmail.com',
authority: 'guest',
userName: 'Lev'
}
]
$scope.openModal = false;
$scope.openModalFunc = function(user) {
$scope.openModal = true;
$scope.selectedUser = user;
Materialize.toast('Awesome, we did it!', 4000);
}
}]);
编辑用户.html
<div id="edit-user" class="modal col l3" ng-controller="UsersController">
<div class="modal-content">
<h4>{{selectedUser.userName}}</h4>
</div>
<div class="modal-footer">
<a class="modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
</div>
</div>
如果
它不是很大的应用程序,那么您可以使用一个控制器的$broadcast
并使用$on
捕获它。您可以在此处找到更多信息。
我发现更好的解决方案是将需要共享的数据移动到较高的常规范围内。