1

我有一個控制器,我在兩個地方使用:在ng-view和ng-include中。這些地方不是彼此的孩子或父母,但我想要在ng-view中對ng-include進行一些更改。我怎樣才能做到這一點?如何將不同範圍從一個控制器綁定到另一個控制器?

這裏是plunker與這些部分的代碼。

我想單擊「編輯用戶」時,表中的user.userName將顯示在彈出窗口中。

的index.html

<body> 
    <div ng-view></div> 
    <div ng-include="'edit-user.html'"></div> 

    <script src="app.js"></script> 
    <script src="UsersController.js"></script> 
    </body> 

app.js

var app = angular.module('myApp', ['ngRoute', 'ui.materialize']) 
    .config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { 
     $routeProvider 
      .when('/', { 
       templateUrl: 'users.html', 
       controller: 'UsersController' 
      }) 
      .otherwise({redirectTo: '/'}); 
    }]); 

users.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> 

UsersController.js

app.controller('UsersController', ['$scope', function($scope) { 
    // create fake users 
    $scope.users = [ 
     { 
      displayName: 'Alexander', 
      registered: '02-07-2017', 
      updated: '02-07-2017', 
      email: '[email protected]', 
      authority: 'admin', 
      userName: 'Alex' 
     }, 
     { 
      displayName: 'Lev', 
      registered: '02-07-2017', 
      updated: '02-07-2017', 
      email: '[email protected]', 
      authority: 'guest', 
      userName: 'Lev' 
     } 
    ] 

    $scope.openModal = false; 

    $scope.openModalFunc = function(user) { 
     $scope.openModal = true; 
     $scope.selectedUser = user; 
     Materialize.toast('Awesome, we did it!', 4000); 
    } 
}]); 

編輯user.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> 
+0

@lin我更新了我的問題。 –

回答

0

如果不是非常大的應用程序,那麼你可以使用$broadcast從一個控制器和捕捉,使用$on .. 你可以找到更多信息here

相關問題