我想與兩個控制器共享數據,但我的應用程序有一個錯誤。當我第一次點擊x2時,它會返回NAN
,但第二次它可以正常工作。我想解決this question。在angularjs中共享控制器中的數據
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>
你的代碼似乎工作正常;我看到NaN的唯一時間是當「輸入數字」字段之一爲空時。 – Boris
爲什麼你需要兩個控制器?任何特定的目的? –