1

I'm new to angular.js. I just want to display "Welcome" message which is 'ControllerB' when clicking a button which is in 'ControllerA'. I tried this by using 'service' but I didn't get how to do. Here is my HTML code:

<body ng-app='myApp'>
    <script src="js/angular.js"></script>
    <script src="script/service.js"></script>
    <div ng-controller='contA'>

        <input type="button" ng-click="clicked()" value="Click">

    </div>
    <div ng-controller='contB'>
        <div ng-show="clickShow">
            <h1>Welcome</h1>
        </div>
    </div>
</body>

And my JS code:

var app = angular.module('myApp',[]);

app.controller('contA', ['$scope', 'displayServ', function(scope,displayServ){        
    scope.clicked = function(){
        displayServ.disp = true;            
    }       
}]);

app.controller('contB',['$scope', 'displayServ', function(scope,displayServ){        
    scope.clickShow = displayServ.disp;       
}]);

app.service('displayServ', function(){
    this.disp = false;
});
disciple
  • 252
  • 1
  • 3
  • 13

2 Answers2

1

You will have to bind to disp property of the service object directly because scope.clickShow is not going to change by itself - there is no connection between service disp and scope clickShow.

So you can expose service object directly into template:

var app = angular.module('myApp',[]);

app.controller('contA', ['$scope', 'displayServ', function(scope,displayServ){        
    scope.clicked = function(){
        displayServ.disp = true;            
    }
}]);

app.controller('contB',['$scope', 'displayServ', function(scope,displayServ){        
    scope.displayServ = displayServ;       
}]);

app.service('displayServ', function(){
    this.disp = false;
});

and in template then:

<body ng-app='myApp'>
    <script src="js/angular.js"></script>
    <script src="script/service.js"></script>
    <div ng-controller='contA'>
        <input type="button" ng-click="clicked()" value="Click">    
    </div>
    <div ng-controller='contB'>
        <div ng-show="displayServ.disp">
            <h1>Welcome</h1>
        </div>
    </div>
</body>

Otherwise you would have to use scope.$watch, but this is not recommend in this case.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

You could use $Broadcast to show the effect in the other controller

Shamal Perera
  • 1,611
  • 1
  • 18
  • 21