Friday, 15 June 2012

javascript - Accessing $scope properties from inside a service in AngularJS -



javascript - Accessing $scope properties from inside a service in AngularJS -

i trying create constructor function within angular service, utilize within of different angular controllers. problem is, object generated constructor needs access 1 of properties on $scope object in order function correctly.

i have implementation working functionality after, involves passing $scope object constructor function parameter. there improve way accomplish this? there issues way have implemented?

html:

<div ng-app="myapp"> <div ng-controller="mycontroller"> <input type="text" ng-model="hello" /> <br/>{{hello}} <br/>{{hellosayer.hello}} <br/>{{hellosayer.hellolength()}} </div> </div>

javascript:

var myapp = angular.module('myapp', []); myapp.controller('mycontroller', function mycontroller($scope, myservice) { $scope.hello = 'hello controller'; $scope.hellosayer = new myservice.hellosayer($scope); }); myapp.factory('myservice', function () { var hellosayer = function (controllerscope) { this.hello = 'hello service'; this.hellolength = function () { homecoming controllerscope.hello.length; }; }; homecoming { hellosayer: hellosayer }; });

here working code in fiddle: http://jsfiddle.net/dbqz4/

you not want passing scopes around, complicated beasts. more point, general rule thought explicit passing around. don't send cow if need glass of milk.

var myapp = angular.module('myapp', []); myapp.controller('mycontroller', function mycontroller($scope, myservice) { $scope.hello = 'hello controller'; $scope.hellosayer = new myservice.hellosayer($scope.hello); }); myapp.factory('myservice', function () { var hellosayer = function (controller_hello) { this.hello = 'hello service'; this.hellolength = function () { homecoming controller_hello.length; }; }; homecoming { hellosayer: hellosayer }; });

javascript angularjs angularjs-scope angularjs-service

No comments:

Post a Comment