Ivan Timoshin
Ivan Timoshin

Reputation: 579

Use one AngularJS code from different pages

Is there a way to call one AngularJS code(function) from different pages? I've found 2 ways, but they aren't solve the problem.

First way is to use a $rootScope. Then logic of my function will be placed into $rootScope.

var sharedFunctions=angular.module('shared',['$rootScope']);

sharedFunctions.run(
    function($rootScope){
       $rootScope.translate=function(language, text){
               for (var i = 0; i < text.translatedTexts.length; i++) {
                   if (text.translatedTexts[i].language == language) {
                       return text.translatedTexts[i];
                   }
               }           
       };
    }
);

But I'll still have to create a function inside my controller, that call $rootScope fuction.

$scope.translate=function(language,text){
    $rootScope.translate(language,text);
}

Second way is simular to first way, but difference is logic part of my function will be placed in service or factory.

Reason, why I won't take these solutions: I'll have to write code(just a few lines, that call main logic) in each controller.

Upvotes: 0

Views: 51

Answers (1)

Ivan Timoshin
Ivan Timoshin

Reputation: 579

Finally, i've discoveret how to share code between the views.

Step 1: create root module and configure basic functionality.

'use strict';
var app=angular.module('rootApp',['ngRoute','appFactories']);

app.run(function($rootScope) {
    $rootScope.translate = function (language, text) {}
    //other functions
});

app.filter('filterName', function() {
   .....
});
//other filters

Step 2: create submodule for my view and add root module as dependency

'use strict';
var cardEditApp=angular.module('submoduleApp',['ngFileUpload','rootApp']);

Step 3: in my view use ng-module="submoduleApp" with name of my submodule. Then I'll can use functionality of the controller of my submodule and functionality of root module.

Upvotes: 0

Related Questions