Angular Js : 单击按钮从两个控制器获取数据并在第三个控制器中显示
Angular Js : Button click to get data from two controllers and showing it in third
我是 AngularJS 的新手。我有以下功能,我有一个 FirstName 字段和 LastName 字段(在两个不同的控制器中),然后单击一个按钮我想在第三个 Controller 中显示 FullName(First Name + Last Name)。请建议我该怎么做。这是我的代码:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="Data.FirstName">
<br>FirstName is : {{Data.FirstName}}</strong>
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="Data.LastName">
<br>LastName is : {{Data.LastName}}</strong>
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getName(Data)">Get full Name</button>
FullName is : {{getName(Data)}}
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { FirstName: '',LastName:'' };
});
myApp.controller('FirstController', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('SecondController', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('ThirdController', function ($scope, Data) {
$scope.Data = Data;
$scope.getName = function (Data)
{
$scope.Data = Data;
}
});
</script>
</body>
</html>
您没有将您的服务正确地注入您的控制器 - 请参阅此 fiddle
同时从您的 getName() 调用中删除数据参数:
<button ng-click="getName()">
我是 AngularJS 的新手。我有以下功能,我有一个 FirstName 字段和 LastName 字段(在两个不同的控制器中),然后单击一个按钮我想在第三个 Controller 中显示 FullName(First Name + Last Name)。请建议我该怎么做。这是我的代码:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="Data.FirstName">
<br>FirstName is : {{Data.FirstName}}</strong>
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="Data.LastName">
<br>LastName is : {{Data.LastName}}</strong>
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getName(Data)">Get full Name</button>
FullName is : {{getName(Data)}}
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { FirstName: '',LastName:'' };
});
myApp.controller('FirstController', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('SecondController', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('ThirdController', function ($scope, Data) {
$scope.Data = Data;
$scope.getName = function (Data)
{
$scope.Data = Data;
}
});
</script>
</body>
</html>
您没有将您的服务正确地注入您的控制器 - 请参阅此 fiddle
同时从您的 getName() 调用中删除数据参数:
<button ng-click="getName()">