1

why in this script:

<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>

function test is called? I want this function called only when I want.

Answer

        app.run(
            function () {
                angular.element.prototype.test = function ( ) {
                    alert ( "da" );
                }
            }
        );
7
  • why I haven't other details. mentioned 7 times? Commented Jan 8, 2016 at 21:42
  • is angular.element.prototype a common way to interact with angular? Commented Jan 8, 2016 at 21:43
  • @PankajParkar , stackoverflow says: You have more code than information, what more information? Commented Jan 8, 2016 at 21:44
  • @dandavis Yes, angular.element -> JQLite Commented Jan 8, 2016 at 21:44
  • @PankajParkar Maybe to meet the minimum length requirement for a post. Commented Jan 8, 2016 at 21:46

1 Answer 1

4

Assignment statements can be evaluated to their values. If you do something like

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

x is assigned, then evaluated, in the if statement.

In your sample,

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

evaluates the function that you assigned to angular.element.prototype.test, effectively passing that function to app.run(). app.run() takes it and, as one would expect, runs it.

If you simply wanted it to make the assignment in the run() execution, you need to instead pass it a function that does that, like this:

app.run(function(){
    angular.element.prototype.test = function ( ) {
        alert ( "da" );
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

I just putted that function in another function, and it works
Great, that's exactly how it should be. If this answered your question, you should mark it as the answer so people will know it's resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.