从angularJS

时间:2016-02-02 09:04:31

标签: javascript html angularjs

我是AngularJS的新手,我想知道为什么在下一段代码中,服务的“randomN”属性没有在$ scope更新。 因为我在控制器上用

引用对象的服务
$scope.srvRandom = srvRandom; 

为什么srvRandom.randomN的更改未生效?

我认为问题在于“randomN”取值为“r”而不是对它的引用,但我不知道如何使其工作。

var app = angular.module("app", []);

    app.controller("cont", ['$scope','srvRandom', function ($scope, srvRandom) {        

    $scope.srvRandom = srvRandom;  
}]);

app.factory("srvRandom", ["$interval", function ($interval) {

    var randomCreator;
    var r;

    return {
        start: function () {
            console.log("START")
            randomCreator = $interval(function () {
                r= Math.random() * 10;
            }, 2000);
        },
        stop: function () {
            console.log("STOP")
            $interval.cancel(randomCreator);
        },
        randomN: r
    };
}]);

HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js"></script>
    <script src="test.js"></script>
</head>
<body ng-app="app" ng-controller="cont">        
    RandomNumber: {{srvRandom.randomN}}
    <div>
        <button ng-click="srvRandom.start()">START!</button>
        <button ng-click="srvRandom.stop()">STOP!</button>
    </div>
</body>
</html>

谢谢!

3 个答案:

答案 0 :(得分:0)

您正在访问始终为srvRandom.randomN的{​​{1}}。

0

我认为你应该这样做

...
randomN: 0
...

答案 1 :(得分:0)

只需更新你的start方法,将其用于当前对象而非window对象。

start: function() {
   var that = this; //store this reference to a variable
   randomCreator = $interval(function() {
       that.randomN = Math.random() * 10; // use here
   }, 2000);
},

答案 2 :(得分:0)

执行此操作$scope.Random = srvRandom;创建服务obj的本地实例

var app = angular.module("app", []);

app.controller("cont", ['$scope', 'srvRandom',
  function($scope, srvRandom) {
    
    $scope.random = 0;
    
    $scope.$watch('getRandom()',function(newv){
        $scope.random = newv;
    });
    $scope.start = function(){
      srvRandom.start();
    }
    $scope.stop = function(){
      srvRandom.stop();
    }
    $scope.getRandom = function(){
      return srvRandom.getRandom();
    }
  }
]);

app.factory("srvRandom", ["$interval",
  function($interval) {

    var randomCreator;
    var randomN = 0;

    return {
      start: function() {
        console.log("START")
        randomCreator = $interval(function() {
          randomN = Math.random() * 10;
        }, 2000);
      },
      stop: function() {
        console.log("STOP")
        $interval.cancel(randomCreator);
      },
      getRandom: function() {
        return randomN;
      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="cont">
  RandomNumber: {{random}}
  <div>
    <button ng-click="start()">START!</button>
    <button ng-click="stop()">STOP!</button>
  </div>
</body>