【问题标题】:Angular script gets executed (fired) after page load页面加载后,Angular 脚本被执行(触发)
【发布时间】:2017-02-03 02:06:02
【问题描述】:

代码如下:

<html>
    <head>
        <script type='text/javascript'>
            var myAppModule = angular.module('myApp', []);

            myAppModule.factory('studentFactory', function (){
                // The whole factory goes here.
            });

            myAppModule.controller('studentsController', ['$scope', 'studentFactory', function ($scope, studentFactory){
                $scope.students = [];
                studentFactory.getStudents(function (data){
                    $scope.students = data;
                });
                studentFactory.removeStudent(function (data){
                    alert('test');
                    $scope.students = data;
                });
            }])
       </script>
</head>
<body ng-app='myApp'>
    ...
</body>
</html>

alert('test') 在页面加载时被触发。我该如何解决?请不要介意代码中的问题,我只是在处理它。

这是 Plunker 中的代码:https://plnkr.co/edit/u7c13AIdKPjmdkzRUPXd?p=preview

【问题讨论】:

  • 我们能看到.removeStudents 的实现吗?还有.getStudents?它们很可能不是异步的。
  • 当然,最好转到我稍后在编辑中提供的 Plunker 中的链接。
  • 另外,还没有实现。
  • 您希望什么时候解雇 removeStudent?你想在点击事件发生时触发它吗?你想在一段时间后触发它吗?

标签: javascript angularjs


【解决方案1】:

这是因为您在实例化时调用了控制器中的 removeStudents 函数。如果您希望它在触发之前等待某个事件,则需要将其绑定到该事件。例如,您可以将其包装在一些点击函数中,如下所示:

$scope.whenIClickMyButton = function () {
    studentFactory.removeStudent(function (data){
        alert('test');
        $scope.students = data;
    });
}

<button ng-click="whenIClickMyButton()">Click Me</button>

并将其添加为点击事件。现在,每次您实例化控制器时都会触发它,因为您每次都在调用它。

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2012-06-08
    相关资源
    最近更新 更多