0

Is it considered better practice to use a custom object vs $scope properties in AngularJS controllers?

Or is it better to attach the plateCheck properties to the $scope of the controller?

Object Version

app.controller('PlateCheckCtrl', ['$scope', 'PlateCheckService', function ($scope, PlateCheckService) {
    var plateCheck = {
        plateNumber: '',
        message: '',
        alertClass: '',
        checkPlate: function (plateNumber) {
            var _this = this;

            PlateCheckService.checkPlate(plateNumber).then(function (response) {
                _this.message = response.message;
                _this.alertClass = response.alertClass;
            });
        }
    };

    $scope.plateCheck = plateCheck;
}]);

$scope Version

app.controller('PlateCheckCtrl', ['$scope', 'PlateCheckService', function ($scope, PlateCheckService) {
    $scope.plateNumber = '';
    $scope.message = '';
    $scope.alertClass = '';
    $scope.checkPlate: function (plateNumber) {
        PlateCheckService.checkPlate(plateNumber).then(function (response) {
            $scope.message = response.message;
            $scope.alertClass = response.alertClass;
        });
    };
}]);

I thought I had read somewhere that if you were not referencing your $scope objects/properties with a . you were doing it wrong.

<input type="text" data-ng-model="object.property" /> <-- Right Way
<input type="text" data-ng-model="property" /> <-- Wrong Way

1 Answer 1

3

The object version is preferred.

From the angularjs wiki on prototypical inheritance.

This issue with primitives can be easily avoided by following the "best practice" of >always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the ?>primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use rather than .

If you really want/need to use a primitive, there are two workarounds:

Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from >creating its own property. Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.