我是 Angular js 的新手。我见过类似的问题,但我不明白。 我有 2 个 Controller
userControllers.controller('RatingCtrl', function($scope,$http,$rootScope,$route)
userControllers.controller('otherProfileCtrl', function ($scope, $routeParams, $rootScope, $http, $location, $window, $timeout,$uibModal, $compile)
RatingCtrl和otherProfileCtrl,这两个模块是相互关联的。我的需要是,我使用 $route.reload();
从 otherProfileCtrl 重新加载 RatingCtrl。有没有办法在没有 uisng 服务的情况下执行此操作?请帮助
最佳答案
您可以将事件从一个 Controller 传递到另一个 Controller 以实现这一目标。然后你会做类似的事情:
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
发送消息。这就是您正在寻找的功能。
话虽如此,在服务中实现共享行为会更好,因为跟踪所有自定义事件可能特别困难。
希望这有帮助。
关于javascript - 从另一个 Controller 重新加载一个 Controller Angular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37740574/