2016-06-10 83 views
0

我是新來的Angular js.我看到了類似的問題,但我不明白這一點。 我有2個控制器從另一個控制器重新加載一個控制器Angular js

userControllers.controller('RatingCtrl', function($scope,$http,$rootScope,$route) 
userControllers.controller('otherProfileCtrl', function ($scope, $routeParams, $rootScope, $http, $location, $window, $timeout,$uibModal, $compile) 

RatingCtrl和otherProfileCtrl,這兩個模塊是相互關聯的。我需要的是,我從otherProfileCtrl使用$route.reload();。就是有沒有辦法做到這一點沒有uisng服務重裝RatingCtrl?plz幫助

+0

你爲什麼不想使用服務? – Guillaume

+0

我認爲這很難。如果只有通過服務纔可能,我可以試試這種方式 – sulu666

回答

4

你可以通過從一個控制器到另一個事件,以實現這一目標。那麼你會做這樣的事情:

var app = angular.module('myApp', []); 
 

 
app.controller('firstController', ['$scope', '$rootScope', 
 
    function($scope, $rootScope) { 
 

 
    $scope.text = 'Initial text'; 
 
    $scope.changeText = function(message) { 
 
     $scope.text = message; 
 
    }; 
 

 
    $rootScope.$on('customEvent', function(event, message) { 
 
     $scope.changeText(message); 
 
    }); 
 

 
    } 
 
]); 
 

 
app.controller('secondController', ['$scope', 
 
    function($scope) { 
 

 
    $scope.message = 'Message from second controller'; 
 

 
    $scope.sendEvent = function() { 
 
     $scope.$emit('customEvent', $scope.message) 
 
    }; 
 

 
    } 
 
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
    <div ng-controller="firstController"> 
 
    <h2>This is the fist controller:</h2> 
 
    <p>{{text}}</p> 
 
    </div> 
 
    <div ng-controller="secondController"> 
 
    <h2>This is the second controller:</h2> 
 
    <input type="text" ng-model="message" /> 
 
    <br> 
 
    <button ng-click="sendEvent()">Send message</button> 
 
    </div> 
 

 
</div>

這裏,firstController聽傳播到$rootScope事件,以及secondController發送消息。這是您正在尋找的功能。這就是說,在服務中實現共享行爲會更好,因爲跟蹤所有的自定義事件可能特別困難。

希望這會有所幫助。

+0

謝謝,如果我們試圖做同樣的事情,但在兩個不同的應用程序中,它工作正常 – sulu666

+0

...我們需要什麼變化?意味着我有2個控制器在2個不同的應用程序(在同一個項目中) –

+0

@NullPointer假設你正在使用Angular 1. *,我想不出在兩個完全獨立的模塊之間正確做到這一點的方法。也就是說,如果模塊之間存在層次結構(例如依賴於另一個模塊),則應該使用相同的解決方案,因爲只有一個根作用域。儘管如此,我的角度相當生疏。 – Kazimieras

相關問題