blue-sky
blue-sky

Reputation: 53896

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 ?

Upvotes: 1

Views: 57

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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

Upvotes: 2

Related Questions