angularjs - Reuse a function inside another controller which is not attached with view -
i trying reuse function inside controller belongs page. has not been attached view of current page. followed these steps:
- include controller using script tag
- use $on , $emit in order call function
unfortunately, nothing happened. controller still initialized not receive calling $emit.
i appreciate if can me figure out.
why want that? angularjs has concept services meant purpose - code reusability. need create service, , inject in controllers use it. see below.
app.service('hexafy', function() { this.myfunc = function (x) { return x.tostring(16); } });
and in controller,
app.controller('myctrl1', function($scope, hexafy) { $scope.hex = hexafy.myfunc(255); }); app.controller('myctrl2', function($scope, hexafy) { $scope.hex = hexafy.myfunc(1023); });
remember services in angular singleton.
Comments
Post a Comment