简体   繁体   中英

ng-init pass value by new obj

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('John','Doe')"> First Name: <input type="text" ng-model="person.firstName"><br> Last Name: <input type="text" ng-model="person.lastName"><br> <br> Full Name: {{person.sayGreeting('1')}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl2', function ($scope) { function Person(fName,lName){ this.firstName = fName; this.lastName = lName; this.sayGreeting = function(lan){ if(lan=="1") return '1 : ' + this.firstName+' '+this.lastName; else return '2: ' + this.firstName+' '+this.lastName; } } } }); </script> </body> </html>

This is a code with a few modifications, I hope it can help you.

  <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myapp" ng-controller="myCtrl2" ng-init="person = Person('John','Doe')"> First Name: <input type="text" ng-model="person.firstName"><br> Last Name: <input type="text" ng-model="person.lastName"><br> <br> Full Name: <label>{{sayGreeting('1')}}</label> </div> <script> var app = angular.module('myapp', []); app.controller('myCtrl2', function ($scope) { $scope.person={}; $scope.Person= function(fName,lName){ $scope.person.firstName = fName; $scope.person.lastName = lName; return $scope.person; } $scope.sayGreeting = function(lan){ if(lan=="1") return '1 : ' + $scope.person.firstName+' '+ $scope.person.lastName; else return '2: ' + $scope.person.firstName+' '+ $scope.person.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