How to call factory methods from HTML in angularjs?

前端 未结 3 588
予麋鹿
予麋鹿 2020-12-30 20:21

In controller I have followed methods:

var isPaused  = false; 

$scope.switcher = function (booleanExpr, trueValue, falseValue) {
    return boo         


        
相关标签:
3条回答
  • 2020-12-30 20:40

    Using AngularJS 1.7.2 and Page Controller (Every Webpage has it's own controller)

    First take the Factory view:

    AppName.factory('eventMate', function() {
        let obj = this;
    
        obj.search = "";
    
        obj.setSearchValue = function(value) {
            obj.search = value;
            return obj.search;
        };
    
        obj.getSearchValue = function() {
            return obj.search;
        };
    
        return obj;
    });
    

    In one of the child Controller, named rfcController

    AppName.controller("rfcController", function ($scope, $http, $filter, $window, $location, $anchorScroll,
                                                   textMate, datetimeMate, restpack, pagination, imageMate, eventMate) {
    
        //there are many more service providers and injectors also, just showing for an idea
        $scope.eventMate = eventMate;
    
    
        $scope.getFiltered = function(){
            let searchValue = $scope.eventMate.getSearchValue().toString();
    
            if(searchValue === undefined){
                return "";
            } else {
                return searchValue.toString();
            }
        };
    }
    

    Now see the source through html side, where I will call this method.

    <table>
        <tr class="rfc_table_td_tr" ng-repeat="(key, value) in rfcDetails | filter:getFiltered()">
            <td>{{value.createdDate}}</td>
            <td>{{value.rfcTitle}}</td>
            <td>{{value.rfcDetails}}</td>
        </tr>
    </table>
    

    Hope it will help many one. :D

    0 讨论(0)
  • 2020-12-30 20:41

    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;
    });
    
    0 讨论(0)
  • 2020-12-30 20:43

    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.

    1. At the highest element surrounding the context in question,
    2. Call the method using the ng-show directive.
    3. The method will run prior to displaying the page.
    4. Note you can also use a solution like this to make sure that bootstrapping work is finished prior to displaying a page (this can reduce the number of moving parts in a scattered rendering)

    <div ng-show="runThisMethod(someVarOnScope)" .....>

    0 讨论(0)
提交回复
热议问题