我是 AngularJs 的新手,所以请耐心等待。
我有以下 Angular 应用程序,其中包含两个 Controller
(function () {
angular.module("app-machines", ['ngFlatDatepicker'])
.controller('mainController', ['$scope', mainController])
.controller("machinesController", machinesController);;
function mainController($scope) {
$scope.datepickerConfig_From = {
allowFuture: true,
dateFormat: 'DD.MM.YYYY',
minDate: moment.utc('2015-09-13'),
maxDate: moment.utc('2015-09-17')
};
$scope.datepickerConfig_To = {
allowFuture: true,
dateFormat: 'DD.MM.YYYY',
minDate: moment.utc('2015-09-13'),
maxDate: moment.utc('2015-09-17')
};
$scope.date_from = "14.09.2015";
$scope.date_to = "15.09.2015";
$scope.change = function () {
//somehow execute machinesController get function
};
}
function machinesController($http) {
var vm = this;
vm.errorMessage = "";
vm.machines = [];
$http.get("/api/machine/2015-09-14_2015-09-16")
.then(function (response) {
//success
angular.copy(response.data, vm.machines);
}, function (error) {
//failure
vm.errorMessage = "Failed to load data:" + error;
});
}
})();
我的 machinesController
应该调用带有参数的 GET
函数。这里的参数是 2015-09-14,第二个参数是 2015-09-16(现在它们是硬编码的)。
我想要实现的是,我的主页上有两个输入控件,它们触发 $scope.change
函数(位于第一个 mainController< 的底部
)。在这里,我想将 date_from
和 date_to
的值传递给 GET 函数,以便我可以检索某些值。
我能做的(最后,如果没有任何效果)是将 ode 从 machinesController
复制到我的 mainController
中,这将解决问题。
但是我想学习如何更好地使用它,因此我想学习如何以正确的方式进行操作(在这种情况下从另一个模块调用一个模块)。
为了实现这个目标我需要改变什么?
编辑:
如前所述,我拥有 machinesController 的原因是下载 json 数据并将其显示给用户。所以最后在我的 html 代码中我有以下内容:
<div ng-controller="machinesController as vm" class="col-md-6 col-md-offset-3">
<div class="text-danger" ng-show="vm.errorMessage"> {{ vm.errorMessage }}</div>
<table class="table table-responsive table-striped">
<tr ng-repeat="machine in vm.machines">
<td> {{ machine.name }}</td>
</tr>
</table>
</div>
显示带有机器名称的表格。
最佳答案
你可以通过两种方式激活它:
首先:$broadcast
和 $on
//PUBLISHER
angular.module('myApp').controller('CtrlPublish', ['$rootScope', '$scope',
function ($rootScope, $scope) {
$rootScope.$broadcast('topic', 'message');
}]);
//SUBSCRIBER
angular.module('myApp').controller('ctrlSubscribe', ['$scope',
function ($scope) {
var unbind = $scope.$on('topic', function (event, arg) {
$scope.receiver = 'got your ' + arg;
});
$scope.$on('$destroy', unbind);
}]);
第二:通过共同服务
angular.module('myApp', [], function($provide) {
$provide.factory('msgBus', ['$rootScope', function($rootScope) {
var msgBus = {};
msgBus.emitMsg = function(msg) {
$rootScope.$emit(msg);
};
msgBus.onMsg = function(msg, scope, func) {
var unbind = $rootScope.$on(msg, func);
scope.$on('$destroy', unbind);
};
return msgBus;
}]);
});
并像这样在 Controller 中使用它:
Controller 1
function($scope, msgBus) {
$scope.sendmsg = function() {
msgBus.emitMsg('somemsg')
}
}
Controller 2
function($scope, msgBus) {
msgBus.onMsg('somemsg', $scope, function() {
// your logic
});
}
发件人:Post
关于javascript - 从一个 Controller 调用另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36663503/