Я хочу поделиться данными с двумя контроллерами, но у моего приложения есть одна ошибка. Когда я впервые нажимаю x2, он возвращает NAN
, но во второй раз он работает правильно.
Я пытаюсь решить этот вопрос.
var mainApp = angular.module("mainApp", []);
mainApp.service('MathService', function() {
this.multiply = function(a, b) {
return a * b
}
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a, a);
}
});
mainApp.service('Data', function() {
return {
result: ''
};
});
mainApp.controller('CalcController', function($scope, CalcService, Data) {
$scope.square = function() {
$scope.Data = Data;
$scope.result = CalcService.square(Data.number);
}
});
mainApp.controller('CalcController2', function($scope, MathService, Data) {
$scope.multiply = function() {
$scope.Data = Data;
$scope.result2 = MathService.multiply(Data.number, $scope.number2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp">
<div ng-controller="CalcController2">
<p>
Enter a number:
<input type="number" ng-model="number2">
<button ng-click="multiply()">multiply</button>
<p>Result x*y: {{result2}}</p>
<div ng-controller="CalcController">
<button ng-click="square()">X<sup>2</sup></button>
<p>Result x2:{{result}}</p>
<br>
<p>
Enter a number:
<input type="number" ng-model="Data.number">
</div>
</div>
</div>
</body>
Код работает нормально. Причина в том, что вы оставляете второй ввод пустым и, следовательно, все разрывы размножения. Пожалуйста, проверьте это.
var mainApp = angular.module("mainApp", []);
mainApp.service('MathService', function() {
this.multiply = function(a, b) {
return a * b
}
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a, a);
}
});
mainApp.service('Data', function() {
return {
result: ''
};
});
mainApp.controller('CalcController', function($scope, CalcService, Data) {
$scope.square = function() {
debugger;
Data=$scope.Data;
$scope.Data = Data;
$scope.result = CalcService.square(Data.number);
}
});
mainApp.controller('CalcController2', function($scope, MathService, Data) {
$scope.Data = {number:1};
$scope.multiply = function() {
debugger;
Data=$scope.Data;
$scope.Data = Data;
$scope.result2 = MathService.multiply(Data.number, $scope.number2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp">
<div ng-controller="CalcController2">
<p>Enter a number:
<input type="number" ng-model="number2">
<button ng-click="multiply()">multiply</button>
<p>Result x*y: {{result2}}</p>
<div ng-controller="CalcController">
<button ng-click="square()">X<sup>2</sup>
</button>
<p>Result x2:{{result}}</p>
<br>
<p>Enter a number:
<input type="number" value="0" ng-model="Data.number">
</div>
</div>
</div>
</body>