Search code examples
javascriptjqueryangularjsangularjs-controllerangularjs-factory

AngularJS service not being invoked


In this fiddle I'm attempting to format text by passing it to a service but the service is not being invoked :

http://jsfiddle.net/7MhLd/1038/

code :

<div ng-controller="MyCtrl">
  <div ng-repeat="line in lines">
      <div class="preview">{{parseText(line.text)}}</div>
   </div>
</div>

var myApp = angular.module('myApp', []);

myApp.factory('parseText', function(data) {
    return "textParsed"
});

function MyCtrl($scope) {
    $scope.lines = [{
        text: 'res1'},
    {
        text: 'res2'}];
}

I'm returning textParsed to show the service is not being called - no text is displayed within the div. How to invoke this service & pass parameter line.text ?


Solution

  • You made some mistakes while creating you app.

    • Declare ng-app="myApp" over main div
    • Inject factory dependency inside your app.
    • return object from factory that can have serveral method like parse
    • Use modularize approach while adding controller, do attach angular component by creating a module.

    Markup

    <div ng-app="myApp" ng-controller="MyCtrl">
        <div ng-repeat="line in lines">
            <div class="preview">{{parseText.parse(line.text)}}</div>
        </div>
    </div>
    

    Code

    var myApp = angular.module('myApp', []);
    
    myApp.factory('parseText', function () {
    
        var parse = function(val){
            //you could have parsing logic here over your variable
            return val + " something";
        }
        return {
            parse: parse
        }
    });
    
    myApp.controller('MyCtrl', MyCtrl)
    
    function MyCtrl($scope, parseText) {
        $scope.parseText = parseText;
        $scope.lines = [{
            text: 'res1'
        }, {
            text: 'res2'
        }];
    };
    

    Working Fiddle