我是棱角分明的新人。我想首先访问另一个控制器范围我想知道简单的方法和可用的方法来做到这一点,提前谢谢
<body ng-app="myApp">
<div ng-controller="myCtrl">
First Name: <input type="text" ng-model="fName"><br><br>
Last Name : <input type="text" ng-model="lName">
<p ng-bind="fullName()"></p>
</div>
<div ng-controller="mySecondCtrl">
Father Name: <input type="text" ng-model="fathName"><br><br>
Mother Name:<input type="text" ng-model="mothName">
<p>
<strong>Paren name:</strong>
<span>Mr.{{fathName}},</span>
<span>Ms.{{mothName}}</span>
</p>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp",[]);
app.controller("myCtrl",myFunction);
function myFunction($scope){
$scope.fName = "";
$scope.lName = "";
$scope.fullName = function(){
return $scope.fName +" "+ $scope.lName
}
}
app.controller("mySecondCtrl",mySecondFunction);
function mySecondFunction($scope){
//I want to access the fullName() function here
}
</script>
</body>
答案 0 :(得分:0)
您可以通过使用Angular服务进行数据传输来实现此目的。您需要在myCtrl
,$scope.fullName
中将方法设置为数据传输服务。
现在,服务将您的方法保存在变量中。现在,从第二个控制器mySecondCtrl
,访问数据传输服务中的方法。
现在实际上你已经从第二个控制器调用了第一个控制器中的方法。这是工作示例。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
First Name:
<input type="text" ng-model="fName">
<br>
<br> Last Name :
<input type="text" ng-model="lName">
<p ng-bind="fullName()"></p>
</div>
<div ng-controller="mySecondCtrl">
Father Name:
<input type="text" ng-model="fathName">
<br>
<br> Mother Name:
<input type="text" ng-model="mothName">
<p>
<strong>Paren name:</strong>
<span>Mr.{{fathName}},</span>
<span>Ms.{{mothName}}</span>
</p>
<p><button ng-click="getDetails()">Get Details</button></p>
</div>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", myFunction);
function myFunction($scope, DataTransfer) {
$scope.fName = "";
$scope.lName = "";
$scope.fullName = function () {
//console.log('fullname method called');
return $scope.fName + " " + $scope.lName
}
//Setting the method to a data transfer service
DataTransfer.setUserDetails($scope.fullName);
}
app.controller("mySecondCtrl", mySecondFunction);
function mySecondFunction($scope, DataTransfer) {
//I want to access the fullName() function here
$scope.getDetails = function () {
console.log('Going to call fullname method from second controller');
//Reading the method in first controller inside the second one
var functionItem = DataTransfer.getUserDetails();
var details = functionItem();
console.log(details);
}
}
app.factory('DataTransfer', function () {
var data = {};
return {
getUserDetails: function () {
return data;
},
setUserDetails: function (UserDetails) {
data = UserDetails;
}
};
});
</script>
</body>
</html>
修改
此处在第二个控制器(functionItem
)中的变量中接收该方法,并调用该方法,并将响应数据保存在变量(details
)中。现在,变量details
保存了从第一个控制器获取的用户详细信息。