未捕获的TypeError:self。$ apply不是Angular1.6中的函数

时间:2017-01-13 13:11:36

标签: angularjs

我尝试学习angular1.6,在这个例子中,我不知道我犯了什么错误。

当我点击“获取消息”按钮时,假设在3秒后,在屏幕上打印并在控制台中记录消息变量中的相同文本。

(function() {
	"use strict";
	angular.module('myApp',[])
    .component('myComponent', {
      template: "<button ng-click='$ctrl.scheduleTask()'>Get Message</button><br><p>Message fetched: {{$ctrl.message}}</p>",
      controller: function() {
        self = this;
        self.scheduleTask = function() {
          setTimeout(function() {
            self.$apply(function() {
              self.message = 'Fetched after 3 seconds';
              console.log('message = ' + self.message);
            });
          }, 3000);
        };
      }
    })
})();
<!DOCTYPE html>
<html ng-app="myApp">
<head>
	<meta charset="utf-8" />
	<title></title>
</head>
<body>
	<my-component></my-component>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</html>

1 个答案:

答案 0 :(得分:1)

尝试使用$ scope:

(function() {
    "use strict";
    angular.module('myApp',[])
    .component('myComponent', {
      template: "<button ng-click='$ctrl.scheduleTask()'>Get Message</button><br><p>Message fetched: {{$ctrl.message}}</p>",
      controller: myComponentController
    });

    myComponentController.$inject['$scope'];

    function myComponentController($scope) {
        self = this;
        self.scheduleTask = function() {
          setTimeout(function() {
            $scope.$apply(function() {
              self.message = 'Fetched after 3 seconds';
              console.log('message = ' + self.message);
            });
          }, 3000);
        };
      }
})();

更正确的方法是使用$ timeout:

$timeout

(function() {
    "use strict";
    angular.module('myApp',[])
    .component('myComponent', {
      template: "<button ng-click='$ctrl.scheduleTask()'>Get Message</button><br><p>Message fetched: {{$ctrl.message}}</p>",
      controller: myComponentController
    });

    myComponentController.$inject['$timeout'];

    function myComponentController($timeout) {
        self = this;
        self.scheduleTask = function() {
          $timeout(function() {
              self.message = 'Fetched after 3 seconds';
              console.log('message = ' + self.message);
          }, 3000, true);
        };
      }
})();