AngularJs set variable in view


AngularJs set variable in view : We sometimes need to assign or update variable value in view. There are many ways to update the variable values in view. Here we are going to explain the simplest one. You can use our online editor to edit and run the example code.


AngularJs set variable in view | Update scope variable

You can set the scope variable simply as below-

Html Part

Html Part Contains the following part which sets the variable value –

AngularJs set scope variable in html view Example:

<div ng-app="myApp">  
<div ng-controller="myController">  
 <div style='display:block;'>{{myVar='Hello World!'}} *if you don't want to display this just add display none css.</div>
 <button ng-click="getVarValue()" >Get Value</button> 
</div> 
</div>

The above part will example will update the variable and you can access the updated value as below –

JavaScript Part

The JavaScript Part Contains the following script as below –

AngularJs set scope variable in view Example:

 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.myValue = '';
 $scope.getVarValue = function() {
     alert($scope.myVar);
 };
});
</script>

The update value can be accessed in controller as above.

Complete Part

Now let us combine both part javascript and html to create full example –

AngularJs set scope variable in html view Example:

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.myValue = '';
 $scope.getVarValue = function() {
     alert($scope.myVar);
 };
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
 <div style='display:block;'>{{myVar='Hello World!'}} *if you don't want to display this just add display none css.</div>
 <button ng-click="getVarValue()" >Get Value</button>
		
 
</div> 
</div>
</body>  
</html>      

Try it »

If you run the above example it will produce output something like this –

AngularJs set variable in view Example


Advertisements

Add Comment

📖 Read More