Search code examples
angularjsangularjs-scopeangular-ng-if

angularjs: scope value doesn't get updated in view


there are buttons in detail.html file:

<div ng-controller="test.views.detail">
<div data-ng-repeat="item in details"  scroll>
    <button ng-click="showDetails(item)">The details</button>

in detail.js file

angular.module('test')
.controller('test.views.detail', function($scope) {

    $scope.detailsClicked = false;

    $scope.showDetails = function(item){
        $scope.detailsClicked = true;
    }....

in formDetail.html code:

<div ng-controller="test.views.detail">
{{detailsClicked}}
<div ng-if="detailsClicked">...

Initially it shows false for detailsClicked, when I click on button it goes to showDetails function but value of $scope.detailsClicked never get updated! It is straight forward not sure why it doesn't work:(


Solution

  • This is because you're using the same controller at two places and expecting the scope object to be the same which it is not. Everytime you call ng-controller in your markup a new scope object will be created. If you want them to be based off the same data then use a service.

    Here is an example

    app.controller('test.views.detail', function($scope, detailsClicked) {
    
        $scope.detailsClicked = detailsClicked;
    
        $scope.showDetails = function(item){
            $scope.detailsClicked.isClicked = true;
        }
    });
    

    Create a factory/service which will retain the data, make sure the data is a

    app.factory('detailsClicked', function(){
      var data = {
        isClicked: false
      }
    
      return data;
    });