javascript - How to inject one controller function to another controller using angularjs? -
i have 2 ng-controllers example controller1, controller2, want inject controller2 method in controller1 , want access through js api function using "document.queryselector('[ng-controller=custom-entity-design-ctrl]')". possible get? tried using factory services not working. it's saying error $scope not defined.
source code
**controller1** myapp.controller("controller1",function($scope, $document, $http, $localstorage) { $scope.test1 = function() { alert("test1"); }; }); **controller2** myapp.controller("controller2",function($scope,$http,$compile,$localstorage, $log) { $scope.test2 = function() { alert("test2"); }; });
in detail... want access $scope.test2 method controller1.
i tried using factory not working.
source code:
myapp.factory("testservice", function($compile, $http, $scope) { $scope.test2 = function() { alert("test2"); }; } factory injected in controller1 myapp.controller("controller1",['testservice',function($scope, $document, $http, $localstorage) { $scope.test1 = function() { alert("test1"); }; }]);
can me achieve this.
you @ right path use of .factory()
:
myapp.factory("testservice", function($compile, $http, $scope) { // return things in object. return { name:"angular js", test2 : function(){ alert("test2") } } }); myapp.controller("controller1",['$scope', '$document', '$http', '$localstorage','testservice', function($scope, $document, $http, $localstorage, testservice) { $scope.test1 = function() { alert("test1"); testservice.test2(); // use method testservice. }; }]);
you missing service in function args of controller , when use .factory()
service make sure return in object {}
, object can provide multiple values/methods etc.
Comments
Post a Comment