3197891abd2c7abb0c8381c7f3b5de282a415e58

Using AngularJS $parse Service

  • AngularJS provides $parse service to evaluate expression.
  • In a template AngularJS expression are presented in {{ }}.AngularJS uses $parse under the hood to compile link and display the value in the browser.
  • $parse() method returns a function for the given expression context.The value of the context can be changes using assign() method.
  • In this demo, "We will explore $parse method by using a simple example".
  • Below code has code for this demo.Assignment of context can be done in two different way.approach 1 is about using assign() method to change the context value. approach 2 is using the direct $parse method which return a function to handle the context object.(JSBIN)
<!DOCTYPE html>
<html ng-app="myApplication">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
 <meta charset="utf-8">
 <title>$parse Service</title>
</head>
<body ng-controller="MyController">
 <input type="text" ng-model="inName" ng-change="parseAgain()" placeholder="Enter some string">
 <h1>{{studName}}</h1>
 <input type="text" ng-model="inSubject" ng-change="parseOtherWay()" placeholder="Enter some string">
 <h1>{{subjectName}}</h1>
</body>
<script>
 var myApplication = angular.module("myApplication", []);
 myApplication.controller("MyController",
 function($scope, $parse) {
 var student = {
 name: "Sandeep",
 subject: "Mathematics"
 };
 //appraoch 1 :using assign method.
 var getName = $parse('name'),
 setName = getName.assign;
 $scope.parseAgain = function() {
 $scope.studName = setName($scope, $scope.inName);
 };
 //appraoch 2 :using getter method
 var getSubject = $parse('subject');
 $scope.subjectName = getSubject(student);
 $scope.parseOtherWay = function() {
 $scope.subjectName = getSubject({
 subject: $scope.inSubject
 });
 };
 });
</script>
</html>
  • Output of the above code is embedded below using JSBIN.

$parse Service

Auto and Manual Bootstrapping AngularJS Application AngularJS Template Cache PUT & GET Example
Sandeep

A passionate Blogger and Developer.Love to code for web application using JavaScript.At present I am exploring the Web Component Specification.

11 years ago angularjs 4,632

AltStyle によって変換されたページ (->オリジナル) /