尝试在控制器之间使用Angular服务获取简单的随机生成器。到目前为止:
JS。文件
var myServiceModule = angular.module('myServiceModule',[]);
myServiceModule.controller('SecondController',['$scope','randomizer', function($scope,randomizer){
$scope.initialNumber = 0;
console.log('Initial number in second controller: ' + $scope.initialNumber);
$scope.generateRandom = function(rng){
console.log('called w/ ' + rng );
$scope.initialNumber = randomizer.genRan(rng);
console.log('Randomed: ' + $scope.initialNumber);
}
}]);
myServiceModule.service('randomizer',[function(range){
this.genRan = function(){
console.log('inside genRan');
return (Math.floor(Math.random() * range) + 1 );
}
}]);
HTML文件
<div id="second" ng-controller="SecondController">
<label>Press button to Generate a random number between 1-100:</label>
<button ng-click="generateRandom(100);">Generate</button>
</div>
当我调用服务时,应该传递一个值吗?相反,当调用服务函数调用(.genRan)时,我继续获取NaN值。我是服务新手,正在正常调用函数,但为什么不将值返回给Controller?
答案 0 :(得分:2)
看起来应该将range
定义为genRan
函数中的参数,试试这个:
myServiceModule.service('randomizer', [function() {
this.genRan = function(range) {
console.log('inside genRan');
return (Math.floor(Math.random() * range) + 1 );
}
}]);
答案 1 :(得分:0)
你错过了传递给this.genRan函数中传递给服务的Range,请修改你的代码并传递这样的范围:
myServiceModule.service('randomizer',[function(range){
this.genRan = function(range){
console.log('inside genRan');
console.log(range);
return (Math.floor(Math.random() * range) + 1 );
}
}]);