Suthan Bala
Suthan Bala

Reputation: 3299

AngularJS variable dependent on another variable from the scope

I have the following code for a controller. On the initial load, the closeBtnText gets set properly based on the hasClosebtn, but when that variable gets updated later on, it doesn't get updated. Is using a method to update the only way?

app.controller("appCtrl", function($scope){

    $scope.hasClosebtn = true;
    $scope.closeBtnText = ($scope.hasClosebtn) ? "test" : 'sdffffffff';
    });
});

Upvotes: 0

Views: 223

Answers (2)

κροκς
κροκς

Reputation: 590

If you just need to display it in the DOM, this should work:

<div ng-controller="appCtrl">
    <p>{{ hasClosebtn ? "test" : "sdffffffff" }}</p>
<div>

If you need it stored in $scope.closeBtnText, you can use $watch:

$scope.$watch('hasClosebtn', function(newValue, oldValue) {
    $scope.closeBtnText = newValue ? 'test' : 'sdffffffff';
});

To give some insights why that $scope variable does not get updated in the current code, think of this scenario:

app.controller('appCtrl', function($scope) {
    $scope.hasClosebtn = true;
    $scope.closeBtnText = ($scope.hasClosebtn) ? 'test' : 'sdffffffff';
    // $scope.closeBtnText => 'test'

    $scope.hasClosebtn = false;
    // $scope.closeBtnText => 'test'
});

The flow of the code does not go back to re-evaluate your ternary expression. The detection of the change on $scope.hasClosebtn happens at the $digest cycle.

Upvotes: 1

DB.Null
DB.Null

Reputation: 1194

It doesn't update because your $scope.closeBtnText is initialized to test.

If you add and ngClick to your button that switches the value of the text you will see the change when you click it

Since it is a newcomer's to angular question i am gonna give you the doc link for ngClick for further investigation ngClick

Upvotes: 1

Related Questions