我有以下代码:
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">
这意味着:
是否可以从同一控制器范围之外调用控制器内定义的函数?
我需要这个,因为该函数正在以非常简单的方式操作控制器所拥有的共享对象(例如,单击按钮会改变给定元素的颜色)。
我无法完成这项工作,我们将不胜感激任何帮助。
我认为将一些数据结构声明为全局可以帮助我解决这个问题,但是,我想避免这样做,因为除了它是不好的做法之外,它可能在将来给我带来更多问题。
答案 0 :(得分:3)
如果我理解你的问题比你基本上有的是一个实用功能,它将对你的共享对象起作用并做你有用的事情(即点击按钮改变给定元素的颜色),现在你需要在其范围之外的另一个控制器中的相同行为。你可以通过两种不同的方式实现同样的目标:
1)。创建一个服务并在控制器中使用它,如下所示:
<!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>
优点与缺点:更具有棱角分明的方式,但在每个不同的控制器中添加依赖关系并相应地添加方法的开销。
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>
优点与缺点:通过这种方式,您的所有模板都可以调用您的方法,而无需将其从控制器传递给模板。如果有很多这样的方法,就会污染根范围。
答案 1 :(得分:1)
尝试删除分号
ng-click="DispSize()"
因为它将ng-click指令绑定到该函数。