Ilia Choly
Ilia Choly

Reputation: 18557

ng-click scope properties not updating as expected

I'm confused as to how angular updates properties on the scope. Here's a contrived version of my code. I expected $scope.name to be automatically updated when $scope.open changes.

jsfiddle

view

<div ng-app>
    <div ng-click="click()" ng-controller="MyCtrl">{{name}}</div>
</div>

controller

var MyCtrl = function ($scope) {
    if (typeof $scope.open === 'undefined') {
        $scope.open = true;
    }

    $scope.name = $scope.open ? "ilia" : "choly";

    $scope.click = function () {
        $scope.open = !$scope.open;
    };
};

I can update $scope.name in the click callback, but I was hoping angular could do that for me.

jsfiddle

var MyCtrl = function ($scope) {
    if (typeof $scope.open === 'undefined') {
        $scope.open = true;
        $scope.name = "ilia";
    }        

    $scope.click = function () {
        $scope.open = !$scope.open;
        $scope.name = $scope.open ? "ilia" : "choly";
    };
};

am I doing something wrong, or is this expected behaviour?

Upvotes: 0

Views: 2747

Answers (1)

CD..
CD..

Reputation: 74176

If you want name to be automatically update when open changes you can use $watch:

Registers a listener callback to be executed whenever the watchExpression changes.

Like this:

var MyCtrl = function ($scope) {
    $scope.$watch('open', function () {
        $scope.name = $scope.open ? "ilia" : "choly";
    });

    $scope.open = typeof $scope.open === 'undefined' ? true : $scope.open;

    $scope.click = function () {
        $scope.open = !$scope.open;
    };
};

Working example: http://jsfiddle.net/hbpYK/

Upvotes: 4

Related Questions