33

controller我遵循的方法中:

var isPaused  = false; 

$scope.switcher = function (booleanExpr, trueValue, falseValue) {
    return booleanExpr ? trueValue : falseValue;
};

$scope.isPaused = function () {
    return isPaused;
};

我可以从 HTML 中调用它,例如:

<body  ng-controller="Cntrl">

...
<h4>
 {{ switcher( isPaused(), 'Search Address Mode', 'Search Location Mode' )}}
</h4>
 <div class="btn-group">
    ...     
 </div>

如您所见,如果我得到isPaused()回报false<h4>Search Location Mode</h4>

这是实用程序,因此我想将其定义为factory

feederliteModule.factory('switcher', function () {   
return {
    sw: function (booleanExpr, trueValue, falseValue) {
        return booleanExpr ? trueValue : falseValue;  
    }
  };
});

没有例外,但

当我尝试这样称呼它时:

<h4>
 {{ switcher.sw( isPaused(), 'Search Address Mode', 'Search Location Mode' )}}
</h4>
 <div class="btn-group">
    ...     
 </div>

什么都没发生。

**我添加'switcher'到控制器。

如何从 HTML 调用工厂方法?

(*如果不清楚,欢迎您更改/编辑我的问题)

谢谢,

4

3 回答 3

52

好吧,你真的不应该这样做......但你可以做的是把你的服务对象放在你的 $scope 的一个属性中,然后从那里调用它。

app.controller('MyCtrl', function($scope, switcher) {
   $scope.switcher = switcher;
});
于 2013-05-14T14:15:22.560 回答
3

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)" .....>

于 2013-11-04T22:02:50.713 回答
0

使用AngularJS 1.7.2和页面控制器(每个网页都有自己的控制器)

首先采取工厂视图:

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;
});

在其中一个子控制器中,名为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();
        }
    };
}

现在通过html端查看源码,这里我会调用这个方法。

<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>

希望它会帮助很多人。:D

于 2018-08-08T18:06:25.867 回答