Anes Gongi
Anes Gongi

Reputation: 29

$scope and Angularjs

I'm new at angular and node so I have some problems.

I don't get what $scope do exactly and I don't know how to use it.

When I wrote the code like this, it didn't work

angular.module('app', [])
.controller('settingsCtrl', ['$scope',
    function($scope) {

        //define the date format
        $scope.date= new Date();
        $scope.h = date.getHours();
        $scope.m = date.getMinutes();

        if(6 < $scope.h < 14 && 0 < $scope.m < 60){
            $scope.text='Ok';
        }
    }]);

But when I wrote it like that, it works.

angular.module('app', [])
.controller('settingsCtrl', ['$scope',
    function($scope) {

        //define the date format
        var date= new Date();
        $scope.h = date.getHours();
        $scope.m = date.getMinutes();

        if(6 < $scope.h < 14 && 0 < $scope.m < 60){
            $scope.text='Ok';
        }
    }]);

And this is the HTML code

<div data-ng-controller="settingsCtrl">
    <div class="card">
        <div class="card-header ">
            <p>{{date | date}}</p>
        </div>
        <div class="card-block">
            <p>{{h}}</p>
            <p>{{m}}</p>
            <p>{{text}}</p>
        </div>
    </div>
</div>

Can anyone explain to me what is the difference between the two codes and how to get familiar with the $scope ?

Thanks

Upvotes: 1

Views: 80

Answers (2)

lealceldeiro
lealceldeiro

Reputation: 14958

The error in the first block of code is that you are trying to access the function getHours on an undefined object: date, instead of $scope (where you created the var date).

You should have tried $scope.date like this:

angular.module('app', [])
.controller('settingsCtrl', ['$scope',
    function($scope) {

        //define the date format
        $scope.date= new Date();
        $scope.h = $scope.date.getHours(); // notice here the change to $scope.date.getHours()
        $scope.m = $scope.date.getMinutes(); //idem

        if(6 < $scope.h < 14 && 0 < $scope.m < 60){
            $scope.text='Ok';
        }
    }]);

Upvotes: 2

Vivz
Vivz

Reputation: 6620

Your first code didn't work because there is no object date in your first code. Your date in first code is an instance of $scope. Instead change it like this

angular.module('app', [])
.controller('settingsCtrl', ['$scope',
    function($scope) {

        //define the date format
        $scope.date= new Date();
        $scope.h = $scope.date.getHours();
        $scope.m = $scope.date.getMinutes();

        if(6 < $scope.h < 14 && 0 < $scope.m < 60){
            $scope.text='Ok';
        }
    }]);

In AngularJS, $scope is the application object (the owner of application variables and functions). It is basically the glue between application controller and the view.

For more info: https://docs.angularjs.org/guide/scope

Upvotes: 2

Related Questions