Category: angularjs

Data & behavior without $scope in Angular js

 

In the below post we will learn that how we can pass data & behavior to the view from angular js controller without using $scope directive. You can use JavaScript “this” object and achieve the expected behavior as below.

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><!DOCTYPE html>
<html ng-app="exampleApp">
<head>
<title>My Demo App</title>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("exampleApp", []);
myApp.controller(
"defaultCtrl", function () {
this.message = "Hello without $scope ";
});
</script>
</head>
<body>
<div ng-controller="defaultCtrl as ctrl">
<input name="message" ng-model="ctrl.message" />
<div>
<span ng-bind="ctrl.message"></span>
</div>
</div>
</body>
</html>

In the above code you can see that I am using “this” object to pass a message property from “defaultCtrl” controller. In the html you need to apply controller using “ng-controller” but here you need to declare a variable by using which you can access the controller properties and methods hence, I have declared “defaultCtrl” as “ctrl”.

Next you can access the properties using “ctrl” in the view and you can observe same above. I am binding a input element with controller “message” property using “ctrl.message”.

You can see the output as below.

image

I hope you find this post useful. Thanks for reading . Happy Coding.

Advertisements