Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $scope as one object literal or multiple $scope's

Tags:

angularjs

Lets say I have the following controller

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

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

is there any reason why i should not use object literals

angular.module('scopeExample', [])
    .controller('MyController', ['$scope', function ($scope) {
        $scope.viewModel = {
            greeting: '',
            username: 'World',
            sayHello: function(){
                this.greeting = 'Hello ' + this.username + '!';
            }
        };
}]);
like image 579
R4nc1d Avatar asked Feb 06 '26 11:02

R4nc1d


1 Answers

I personally prefer to use object literal rather than bind everything $scope. Its manageable and good practice.

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

    viewModel.sayHello = function () {
        this.greeting = 'Hello ' + this.username + '!';
    };
    $scope.viewModel = viewModel;
}]);
like image 104
Kashif Mustafa Avatar answered Feb 09 '26 12:02

Kashif Mustafa