我有以下代码:
app.controller('MatrixExpertCtrl', function($scope,$http){
$scope.PassedMatrix=[];
$scope.GetMatrixFromServer=function(){
$http.get("http://localhost:3000/getmatrixfromdb").success(function(resp){
alert("The matrix grabbed from the server is: " + resp[0].ans);
$scope.PassedMatrix.push(resp[0].ans);
});
};
$scope.DispSize=function(){
alert("testing");
alert("The size is "+$scope.PassedMatrix[0].size) ;
};
//$scope.GetMatrixFromServer();
});
现在,假设在 HTML 中,我有这样的内容:
<div class="col-sm-3 col-md-3 col-lg-3">
<div class="text-center">
<h3>Example Survey</h3>
<p>example paragrah</p>
<p>More random text</p>
<p>ending the paragraphs</p>
<button id="updmat" ng-click="DispSize();" type="button" class="btn btn-default">Updates</button>
</div>
//Much more code
<div id="body2">
<div class="col-sm-6 col-md-6 col-lg-6" style="background-color:#ecf0f1;">
<div ng-controller="MatrixExpertCtrl" ng-app="app" data-ng-init="GetMatrixFromServer()">
<div class="text-center">
含义:
是否可以从同一 Controller 的范围之外调用 Controller 内部定义的函数?
我需要这个,因为该函数正在以非常非常简单的方式操作 Controller 拥有的共享对象(例如,单击按钮会更改给定元素的颜色)。
我在完成这项工作时遇到了困难,任何帮助将不胜感激。
我认为将某些数据结构声明为全局会帮助我解决这个问题,但是,我想避免这样做,因为除了这是不好的做法之外,它可能会在未来给我带来更多问题。
最佳答案
如果我正确理解你的问题,那么你基本上拥有的是一个实用函数,它将在你的共享对象上工作并做你有用的事情(即单击按钮改变给定元素的颜色),现在你确实需要在其范围之外的另一个 Controller 中具有相同的行为。您可以通过两种不同的方式实现相同的目标:
1).创建一个服务并使其在您的 Controller 中可用,如下所示:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
changeColour: function() {
alert("Changing the colour to green!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.callChangeColour = function() {
myService.changeColour();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callChangeColour()">Call ChangeColour</button>
</body>
</html>
优点和缺点:更 Angular 方式,但在每个不同的 Controller 中添加依赖项并相应地添加方法会产生开销。
2).通过rootscope访问
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalChangeColour = function() {
alert("Changing the colour to green!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalChangeColour()">Call global changing colour</button>
</body>
</html>
优点和缺点:通过这种方式,所有模板都可以调用您的方法,而无需将其从 Controller 传递给模板。如果有很多这样的方法,就会污染根范围。
关于javascript - 从外部调用 AngularJS Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564008/