In controller
I have followed methods:
var isPaused = false; $scope.switcher = function (booleanExpr, trueValue, falseValue) { return booleanExpr ? trueValue : falseValue; }; $scope.isPaused = function () { return isPaused; };
And I can call it from HTML like:
<body ng-controller="Cntrl"> ... <h4> {{ switcher( isPaused(), 'Search Address Mode', 'Search Location Mode' )}} </h4> <div class="btn-group"> ... </div>
As you see if isPaused()
returns false
I get <h4>Search Location Mode</h4>
This is utility therefore I want to define it as factory
feederliteModule.factory('switcher', function () { return { sw: function (booleanExpr, trueValue, falseValue) { return booleanExpr ? trueValue : falseValue; } }; });
No exceptions but
when I try to call it like:
<h4> {{ switcher.sw( isPaused(), 'Search Address Mode', 'Search Location Mode' )}} </h4> <div class="btn-group"> ... </div>
Nothing happens.
**I added 'switcher'
to controller.
How can I call factory method from HTML?
(*You welcome to change/edit my question if it seems not clear)
Thank you,
What is Factory in AngularJS? Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.
$resource documentation describes it as: A factory which creates a resource object that lets you interact with RESTful server-side data sources. $resource is most powerful when it's configured with a classic RESTful backend.
factory() is a method that takes a name and function that are injected in the same way as in service. The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not.
AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function which allows us to add some logic to a created object and return the created object.
Well, you're not really supposed to do that... but what you can do is put your service object in a property on your $scope, and call it from there.
app.controller('MyCtrl', function($scope, switcher) { $scope.switcher = switcher; });
I had a more general question, "How to call angularjs scope/factory/service from html on page load." My solution was to call the method within ng-show.
<div ng-show="runThisMethod(someVarOnScope)" .....>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With