简体   繁体   中英

Why will always use anonymous function in AngularJS

I see almost tutorial use anonymous function in AngularJS, instead of normal function, like function name(para1) {}. Please see this link: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller_property

I change to normal function, but it cannot work, Please advise. Thanks.

<div ng-app="myApp" ng-controller="personCtrl as main">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{main.fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    function fullName() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
</script>

The idea of $scope is to have an object where all fields and functions are defined on, so that you are able to reference the fields and functions from your template.

When you don't attach the function to $scope it will not be visible for angular to be called. So the contract is that in your controller function, you add everything you need to the $scope object passed by the framework and by doing so, you can later access the fields or call the functions from your template. Everything you reference in directives like ng-model or put into {{ }} will be evaluated by angular, but angular doesn't know what you mean with the expression fullName() as written in your snippet link or fails finding it in the controller when written as main.fullName() .

For details on the concept of $scope have a look at the angular docs on scopes .

What you can do (and it is also a good practice) is to declare your function and then (maybe in tha init of the controlelr) assign them to the $scope ..so is more clear when you'll re read it something like:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = fullName; //<-- here you assign it


    function fullName() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM