Accessing a service from a different module in AngularJS -
i have code have hexafy
service in 1 module want access in different module:
<!doctype html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myapp" ng-controller="myctrl"> <p>the hexadecimal value of 255 is:</p> <h1>{{hex}}</h1> </div> <div ng-app="myapp2" ng-controller="myctrl2"> <p>the hexadecimal value of 155 is:</p> <h1>{{hex2}}</h1> </div> <p>a custom service whith method converts given number hexadecimal number.</p> <script> var app = angular.module('myapp', []); app.service('hexafy', function() { this.myfunc = function (x) { return x.tostring(16); } }); app.controller('myctrl', function($scope, hexafy) { $scope.hex = hexafy.myfunc(255); }); var app2 = angular.module('myapp2', ['myapp']); app2.controller('myctrl2', function($scope, hexafy) { $scope.hex = hexafy.myfunc(155); }); </script> </body> </html>
however, hex2
model in example never gets resolved! doing wrong?
i found solution! per comments below, can have 1 angular app per page many controllers want.
this working solution!
<!doctype html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myapp"> <div ng-controller="myctrl"> <p>the hexadecimal value of 255 is:</p> <h1>{{hex}}</h1> </div> <div ng-controller="myctrl2"> <p>the hexadecimal value of 155 is:</p> <h1>{{hex2}}</h1> </div> <p>a custom service whith method converts given number hexadecimal number.</p> <script> var app = angular.module('myapp', []); app.service('hexafy', function() { this.myfunc = function (x) { return x.tostring(16); } }); app.controller('myctrl', function($scope, hexafy) { $scope.hex = hexafy.myfunc(255); }); app.controller('myctrl2', function($scope, hexafy) { $scope.hex2 = hexafy.myfunc(155); }); </script> </body> </html>
only 1 angularjs application can auto-bootstrapped per html document. first ngapp found in document used define root element auto-bootstrap application. run multiple applications in html document must manually bootstrap them using angular.bootstrap instead.
so define myapp2 div id .
<div id="app2" ng-app="myapp2" ng-controller="myctrl2">
so u have manually bootstrap app2 below
angular.bootstrap(document.getelementbyid("app2"), ['myapp2']);
one more mistake in ur code . hex2 model should set
$scope.hex2 = hexafy.myfunc(155); // $scope.hex before
Comments
Post a Comment