AngularJS运行执行函数

AngularJS Run execute function?

本文关键字:函数 执行 运行 AngularJS      更新时间:2023-09-26

为什么在这个脚本中:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script>
        var app = angular.module( "test", [] );  
        app.run(
            angular.element.prototype.test = function ( ) {
                alert ( "da" );
            }
        );
        app.directive('cacat', function() {
            return {
                restrict: 'E',
                link: function (scope, element, attrs) {
                }
            };
        });
        </script>
    </head>
    <body ng-app="test">
        <cacat></cacat>
    </body>
</html>

调用函数测试?我只想在需要的时候调用这个函数。

回答

        app.run(
            function () {
                angular.element.prototype.test = function ( ) {
                    alert ( "da" );
                }
            }
        );

Assignment语句可以根据其值进行求值。如果你做了类似的事情

var x = false;
if(x = true) { /*Some code here*/ }

if语句中分配x然后求值

在您的样品中,

app.run(angular.element.prototype.test = function ( ) {
            alert ( "da" );
        })

评估分配给angular.element.prototype.test的函数,有效地将该函数传递给app.run()app.run()接受它,正如人们所期望的那样,运行它

如果您只是想让它run()执行中进行赋值,那么您需要向它传递一个这样做的函数,如下所示:

app.run(function(){
    angular.element.prototype.test = function ( ) {
        alert ( "da" );
    });
});