Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - How do I connect this interval service to a view?

The AngularJS documentation for $interval gives an example of using $interval in a controller to manage a timer that the user can play with in a view. You can read the code for the official example at the angularJS documentation page by clicking n this link.

I have tried to move the code from the example controller back into a service so that the code can be more modular. But the app is not connecting the service to the view. I have recreated the problem in a plnkr that you can play with by clicking on this link.

What specific changes need to be made to the code in the plnkr above so that the mytimer service can be available to the view as a property of the controller that imports the service?

To summarize here, 'index.html` is:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example109-production</title>
    <script src="myTimer.js" type="text/javascript"></script>
    <script src="exampleController.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

</head>
<body ng-app="intervalExample">

<div>
  <div ng-controller="ExampleController">
    <label>Date format: <input ng-model="mytimer.format"></label> <hr/>
    Current time is: <span my-current-time="mytimer.format"></span>
    <hr/>
    Blood 1 : <font color='red'>{{mytimer.blood_1}}</font>
    Blood 2 : <font color='red'>{{mytimer.blood_2}}</font>
    <button type="button" data-ng-click="mytimer.fight()">Fight</button>
    <button type="button" data-ng-click="mytimer.stopFight()">StopFight</button>
    <button type="button" data-ng-click="mytimer.resetFight()">resetFight</button>
  </div>
</div>
</body>
</html>

The code for app.js is:

angular.module('intervalExample',['ExampleController'])

The code for exampleController.js is:

angular
.module('intervalExample', ['mytimer'])
.controller('ExampleController', function($scope, mytimer) {

    $scope.mytimer = mytimer;

});

The code for myTimer.js is:

angular
.module('mytimer', [])
.service('mytimer', ['$rootScope', function($rootScope, $interval) {

    var $this = this;
    this.testvariable = "some value. ";

        this.format = 'M/d/yy h:mm:ss a';
        this.blood_1 = 100;
        this.blood_2 = 120;

        var stop;
        this.fight = function() {
          // Don't start a new fight if we are already fighting
          if ( angular.isDefined(stop) ) return;

          stop = $interval(function() {
            if (this.blood_1 > 0 && this.blood_2 > 0) {
              this.blood_1 = this.blood_1 - 3;
              this.blood_2 = this.blood_2 - 4;
            } else {
              this.stopFight();
            }
          }, 100);
        };

        this.stopFight = function() {
          if (angular.isDefined(stop)) {
            $interval.cancel(stop);
            stop = undefined;
          }
        };

        this.resetFight = function() {
          this.blood_1 = 100;
          this.blood_2 = 120;
        };

        this.$on('$destroy', function() {
          // Make sure that the interval is destroyed too
          this.stopFight();
        });

}])

    // Register the 'myCurrentTime' directive factory method.
    // We inject $interval and dateFilter service since the factory method is DI.
    .directive('myCurrentTime', ['$interval', 'dateFilter',
      function($interval, dateFilter) {
        // return the directive link function. (compile function not needed)
        return function(scope, element, attrs) {
          var format,  // date format
              stopTime; // so that we can cancel the time updates

          // used to update the UI
          function updateTime() {
            element.text(dateFilter(new Date(), format));
          }

          // watch the expression, and update the UI on change.
          scope.$watch(attrs.myCurrentTime, function(value) {
            format = value;
            updateTime();
          });

          stopTime = $interval(updateTime, 1000);

          // listen on DOM destroy (removal) event, and cancel the next UI update
          // to prevent updating time after the DOM element was removed.
          element.on('$destroy', function() {
            $interval.cancel(stopTime);
          });
        }
      }]);;

All of the above code is assembled in "working" form in this plnkr that you can use to diagnose and identify the solution to the problem. So what specific changes need to be made to the code above to allow the user to interact with the service through the view?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, you didn't inject the $interval to the mytimer service and did try to use it.

secondly, you had scope issues in the mytimer service:

stop = $interval(function() {
    if (this.blood_1 > 0 && this.blood_2 > 0) {
        this.blood_1 = $this.blood_1 - 3;
        this.blood_2 = $this.blood_2 - 4;
    } else {
        this.stopFight();
    }
}, 100);

when declaring a function you are creating a new scope, meaning the this is pointing to a new scope. you can either use bind or to use the $this variable you declared in line 5. (in ES2015 you could simply use the arrow function).

also you declared the module exampleController twice in app.js and in mytimer.js.

Take a look at this working Plunker:
http://plnkr.co/edit/34rlsjzH5KWaobiungYI?p=preview


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...