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;
});
1

2 Answers 2

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.

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

Comments

0

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

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.