Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted February 16th, 2016
Learning the Scope

For the project I was assigned to work with AngularJS a bit. I’m still learning how to work with AngularJS that’s why I first try to understand the most used expressions. Unlike the other MVC frameworks, AngularJS doesn’t have specific classes or functions to create model objects. It actually extends JavaScript objects with a custom method and properties. This also known as Scope’s in AngularJS terms, works as glue between the view and other parts.

First a simple example of using scopes.

Script.js

angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';

  $scope.sayHello = function() {
    $scope.greeting = 'Hello ' + $scope.username + '!';
  };
}]);

HTML

<div ng-controller="MyController">
  Your name:
    <input type="text" ng-model="username"/>
    <button ng-click='sayHello()'>greet</button>
  <hr />
  {{greeting}}
</div>

In the above example you can see in our input field where we typed in “World” that it’s scoped and set to the .username property in the script. Now by making a new scope sayHello function for our greet button which will trigger our sayHello function we can create the greeting “Hello + $scope.username + ‘!’. That will be “Hello World!”.

There are many sorts of scopes but I’ll explain some scopes inside directive’s because it solved many problems in our project. It’s pretty much a default Scope, (scope: false) the directive will not create a new scope, so there is no inheritance here.
It’s pretty much a default Scope, (scope: false) the directive will not create a new scope, so there is no inheritance here. This is easy, but you are creating a new property on the scope when in fact it is forcing it in an existing property. This is not great for writing directives that will be used more times than once. For reusable components the scope: { } will be best. This is a better choice since the directive cannot accidentally read or modify the parent scope.

These were scopes I saw in the project.

Posted by Michael Netelenbos

Leave a Reply

Your email address will not be published. Required fields are marked *