0

Code in Controller:

    var type = null;
    var title = null;
    var content = null;

    function showMessage(type, title, content) {
      $scope.displayMessage = true;
      $scope.message = {
        type: type,
        title: title,
        content: content
      }
      $timeout(function() {
          $scope.fadeMessageSuccess = true;
      }, 3000);
    };

    var type = "success";
    var title = "Thanks for registering!";
    var content = "Your account has successfully been created!";
    showMessage(type, title, content);

The above is my code that I'm working with and it's inside a controller currently. It works perfectly however I want to clean it and up and use it in multiple controllers. How do I go about wrapping this part in a function to be used throughout the app and then only having to call the last 4 lines in my controllers:

    var type = null;
    var title = null;
    var content = null;

    function showMessage(type, title, content) {
      $scope.displayMessage = true;
      $scope.message = {
        type: type,
        title: title,
        content: content
      }
      $timeout(function() {
          $scope.fadeMessageSuccess = true;
      }, 3000);
    };

I only want to have to write the following code whenever I want to show a message:

var type = "success";
var title = "Thanks for registering!";
var content = "Your account has successfully been created!";
showMessage(type, title, content);

The View:

<div ng-controller="AccountCtrl" ng-cloak="">
  <div class="ui {{message.type}} message message-overwrite"
       ng-class="{'fade': fadeMessageSuccess} "
       ng-show="displayMessage">
    <div class="header">
      {{message.title}}
    </div>
    <p>{{message.content}}</p>
  </div>
</div>
4
  • 2
    Possible duplicate of how to reuse a function in multiple controllers Commented Jan 6, 2017 at 23:31
  • 1
    Check the second answer in the linked question. Creating a service and inject it in the controllers is better solution in my opinion. Commented Jan 6, 2017 at 23:33
  • 1
    Yes but you can't use $scope in a service which is where I get lost. Commented Jan 6, 2017 at 23:36
  • 1
    don't use scope in service. use normal var as usual function. Commented Jan 6, 2017 at 23:40

2 Answers 2

1

As the Angular controller docs suggest, if you want to share code or state across multiple controllers use a service.

With the addition of one argument you can use a MessageService as a utility. You controllers would obviously implement the common functionality which would be the case anyway.

angular.module('app', []);
angular.module('app')
  .factory('MessageService', function() {
    return {
      showMessage: function(ctrl, type, title, content) {
        ctrl.displayMessage = true;
        ctrl.message = {
            type: type,
            title: title,
            content: content
          }
          //...
      }
    };
  })
  .controller('First', ['MessageService',
    function(MessageService) {
      var self = this;
      self.displayMessage = false;
      self.message = {};
      self.firstSrvc = function() {
        MessageService.showMessage(self, "type", "title", "content");
      };
    }
  ])
  .controller('Second', ['MessageService',
    function(MessageService) {
      var self = this;
      self.displayMessage = false;
      self.message = {}
      self.secondSrvc = function() {
        MessageService.showMessage(self, "type2", "title2", "content2");
      };
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="First as f">
    <div ng-controller="Second as s">
      <h3>First: {{f.displayMessage}}</h3>
      <div ng-show="f.displayMessage">
        <h3>{{f.message.type}}, {{f.message.title}}, {{f.message.content}}</h3>
      </div>
      <h3>Second: {{s.displayMessage}}</h3>
      <div ng-show="s.displayMessage">
        <h3>{{s.message.type}}, {{s.message.title}}, {{s.message.content}}</h3>
      </div>
      <div>
        <button ng-click="f.firstSrvc()">First</button>
        <button ng-click="s.secondSrvc()">Second</button>
      </div>
    </div>
  </div>
</div>

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

Comments

0

Simple answer: service .Wrap all your app logic in services. Then you could simply injected in any controller and use it anywhere in your app.

Since this case doesn't have a lot of logic and It's really conected to the view then you could make a custom directive.

One more thing if you are trying to make a tosatr there are tones of already implemented ones. Don't reinvent the wheel.

I hope that helps. Good luck

6 Comments

Yeah but that doesn't work as $scope doesn't work in a service.
I will do a little plunker for you. may be that helps
would you explain to me what is the show messages do, please ?
$scope.displayMessage triggers an ng-show, $scope.message is all the data-binding and the $timeout function triggers a CSS class which hides the object.
I added the view to the original post so it might make more sense.
|

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.