javascript - ng-init 通过新 obj 传递值

标签 javascript html angularjs

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

最佳答案

这是经过一些修改的代码,希望对您有所帮助。

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

关于javascript - ng-init 通过新 obj 传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411081/

相关文章:

javascript - Angular 6 - 添加到 Assets 中的本地文件(js、css、img)在运行时看不到。如何一次引用所有文件?

javascript - 类型错误:无法读取未定义的 React 属性 'any'

javascript - 在打砖 block 游戏中找到距离球最近的砖 block

javascript - 构建真实世界的 AngularJS 应用程序,我应该如何在 html 中声明我的 Controller 。我需要在index.html中声明所有内容吗?

javascript - 重定向图像文件获取请求 Express 4.x 和 Handlebars

html - css 仅在没有空格时中断单词

html - 是否可以添加仅针对特定浏览器显示的 css 样式

html - 在 Opencart 1.5.6.4 中显示完整的面包屑

javascript - 我无法让我的 Angular 应用程序在本地运行

javascript - 获取请求 AngularJs 后滚动到页面底部