如何在angularjs中从HTML调用工厂方法?

Max*_*tin 33 angularjs

在controller我遵循的方法:

var isPaused  = false; 

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

$scope.isPaused = function () {
    return isPaused;
};
Run Code Online (Sandbox Code Playgroud)

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

<body  ng-controller="Cntrl">

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

如你isPaused()所知,false我得到的回报<h4>Search Location Mode</h4>

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

feederliteModule.factory('switcher', function () {   
return {
    sw: function (booleanExpr, trueValue, falseValue) {
        return booleanExpr ? trueValue : falseValue;  
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

没有例外但是

当我试着称之为:

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

什么都没发生.

**我加入'switcher'了控制器.

如何从HTML调用工厂方法?

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

谢谢,

Ben*_*esh 52

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

app.controller('MyCtrl', function($scope, switcher) {
   $scope.switcher = switcher;
});
Run Code Online (Sandbox Code Playgroud)

  • HTML视图只能链接到Controller(使用$ scope变量)或使用Directives扩展.任何其他方式不是一个有角度的方式:) (7认同)
  • 为什么不这么想?它似乎凌乱吗?你的解决方案有效 问题是为什么我需要创建`$ scope.switcher`如果`controller`接收`切换器`标识符.谢谢 (3认同)