Steven Scott
Steven Scott

Reputation: 11250

AngularJS share function/common code in a controller

I have a subroutine I want to use in my controller. In the case or working with data, a new record blanks fields, as would a screen clear, and after some other processes, I would like to clear the editable fields on the view.

Controller:

angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
    function ($scope, ServiceData) {

        function ClearMemberStruture()
        {
            $scope.member.Key = "";
            $scope.member.Name = "";
            $scope.member.Points = 0;
            $scope.EditMode = false;
        }

        $scope.Members = ServiceData.GetAllMembers();
        $scope.member = {};
        ClearMemberStruture();

        $scope.DeleteMember = function(Member) {
            ServiceData.DeleteMember(Member.Key);
            $scopeEditMode = false;
        };

        $scope.EditMember = function(Member) {
            var EditMember = ServiceData.GetOneMember(Member.Key);
            EditMember.$bindTo($scope, "member").then(
                function(unbind) {
                    $scope.MemberUnbind = unbind;
                });
            $scopeEditMode = true;
        };

        $scope.SaveMember = function(Member) {
            if( ! $scopeEditMode )
            {
                $scope.member = ServiceData.AddMember(Member);
                ClearMemberStructure();
            }
        };

        $scope.ClearMember = function() {
            $scope.member.unbind;
            ClearMemberStructure();
            $scope.MemberUnbind();
        };
    }
]);

ClearMemberStructure() is used to reset the common structure fields and the Edit flag which controls showing information on the screen. When I run this code, I always get a

ReferenceError: ClearMemberStructure is not defined

How can I share this common function in my controller in AngularJS?

If I add a Factory, I can achieve this using calls to the factory:

angular.module('MyApp').factory("MemberRecord", function() {
        var Member = {
            Key: "",
            Name: "",
            Points: ""
            };

        return {
            Clear: function() {
                Member.Key = "";
                Member.Name = "";
                Member.Points = "";
                return Member;
            }
        };
    }
);

And then in the controller:

    $scope.member = MemberRecord.Clear();

Is there a way to do the simply function style code sharing, as I do want this to be handled as a private function, but cannot get it to recognize the function in the controller.

Upvotes: 1

Views: 830

Answers (3)

Dmitry Zaets
Dmitry Zaets

Reputation: 3277

I prefer to use factory for Member and encapsulate method there. But you can try the easier way:

angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
    function ($scope, ServiceData) {
        var that = this;
        that.ClearMemberStruture = function()
        {
            $scope.member.Key = "";
            $scope.member.Name = "";
            $scope.member.Points = 0;
            $scope.EditMode = false;
        }

        $scope.Members = ServiceData.GetAllMembers();
        $scope.member = {};
        that.ClearMemberStruture();

        $scope.DeleteMember = function(Member) {
            ServiceData.DeleteMember(Member.Key);
            $scopeEditMode = false;
        };

        $scope.EditMember = function(Member) {
            var EditMember = ServiceData.GetOneMember(Member.Key);
            EditMember.$bindTo($scope, "member").then(
                function(unbind) {
                    $scope.MemberUnbind = unbind;
                });
            $scopeEditMode = true;
        };

        $scope.SaveMember = function(Member) {
            if( ! $scopeEditMode )
            {
                $scope.member = ServiceData.AddMember(Member);
                ClearMemberStructure();
            }
        };

        $scope.ClearMember = function() {
            $scope.member.unbind;
            ClearMemberStructure();
            $scope.MemberUnbind();
        };
    }
]);

Upvotes: 1

aorfevre
aorfevre

Reputation: 5064

   var ClearMemberStruture = function()
    {
        $scope.member.Key = "";
        $scope.member.Name = "";
        $scope.member.Points = 0;
        $scope.EditMode = false;
    }

is your solution to declare ClearMemberStruture without breaking your whole code.

Upvotes: 1

errata
errata

Reputation: 26842

I use a separate file with factories to share code between controllers.

App.factory('CommonServices', function ($http) {


    return { 
      createComment: function($api_key, $post_id, $comment) {
        var comment_data = {
          content: $comment
        };
        return $http({
          url: '/api/v1/posts/' + $post_id + '/comments',
          method: "POST",
          headers: { 'X-API-TOKEN': $api_key },
          params: comment_data,
          data: ''
        })
      }
    });

Then in a controller you can access the common functions like:

$scope.saveComment = function($post_id) {
   CommonServices.createComment($scope.api_key, $post_id, $scope.comment.text)
   .then(function(_data) {
     var index = $scope.feed_items.filter(function (post) { return post.id == $post_id });
     index[0].comments.unshift(_data.data);
     $scope.showComment = false;
   });
 }

Upvotes: 1

Related Questions