javascript - Dependency Injection of functions with Factories (AngularJS) -
i have few functions used in different controllers, , rather copy , paste multiple times controllers, want pull out , place in factory.
however, when try call function in html via angular {{expressions}}
doesn't work.
instead, i've made functions inside each of controllers' $scopes call factory's functions dom can read expressions--but seems redundant. there way fix can call functions factory?
here had tried:
index.html:
<div ng-controller="mycontroller"> rating of item is: {{makegraph.getrating(whichitem)}}<br /> votes of item is: {{makegraph.getvotes(whichitem)}} </div>
mycontroller.js:
controllers.controller('mycontroller', ['$scope', 'makegraph', '$routeparams', function($scope, makegraph, $routeparams){ $scope.whichitem = $routeparams.itemid; //no other reference makegraph here }])
factory.js:
app.factory('makegraph', function(){ var service = {}; service.getrating = function(itemno){ ... return ...; }; service.getvotes = function(itemno){ ... return ...; }; return service; });
instead, can work when change mycontroller have this:
$scope.getrating = function(){ return makegraph.getrating(itemno); };
can fix don't have call function inside $scope? thanks.
add $scope.makegraph = makegraph
controller
controllers.controller('mycontroller', ['$scope', 'makegraph', '$routeparams', function($scope, makegraph, $routeparams){ $scope.whichitem = $routeparams.itemid; $scope.makegraph = makegraph }])
then access makegraph
view
example:
<a ng-click="makegraph.getvotes(12)"> click me </a>
note if return promises in service, still need wrap in controller in order handle .success / .then / .error ...
events
Comments
Post a Comment