Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice when using $scope properties in Angular

I’m working on an application and I’m trying to make sure I’m using $scope correctly.

I watched the best practices video and Miško kinda says we shouldn’t be manipulating $scope properties in this.

I’ve been creating variables like this for the most part:

    $scope.groups = groupService.getGroups()
    $scope.users = userService.getUsers();
    $scope.selectedUser = false;

Should I re-write my application to use something like this instead:

    $scope.model = {
        selectedAvailableGroups: [],
        selectedAssignedGroups: [],
        allGroups: groupService.getGroups(),
        allUsers: userService.getUsers(),
        selectedUser: false
    }

The reason I ask is that I’ve rarely seen examples or applications using $scope.model way, it’s usually just properties declared on $scope.

like image 564
Batman Avatar asked Oct 02 '22 16:10

Batman


1 Answers

You should always have a period in your model names because of the way that javascript searches the inheritance chain. I would advise you refactor as you are suggesting.

To be clear, when you set a primitive property on a javascript object like:

$scope.Name ='Fred'

If Name doesn't exist javascript will create a new property without checking the parent object.

If you do like this:

$scope.Model.Name = 'Fred'

javascript will check the parent(s) all the way up until it either finds Model.Name or finds it is undefined.

like image 178
Mike Cheel Avatar answered Oct 06 '22 01:10

Mike Cheel