2015-06-18 46 views
1

ng-if在HTML模板:如何在AngularJS的多个视图中使用一个函数?

<div ng-if="isImage(item._file) == false"> 

所以,方法isImage()位于电流控制器上。我怎样才能做普通的方法isImage(),我不做重复每个控制器,并可以从视图调用?

+0

服务定义,然后调用该方法 –

+0

如何从模板调用? – Caur

回答

0

我可以告诉你2种方式来做到这一点。 最简单的,但不理想的方式: 在全局控制器或在您的应用程序运行段:

$rootScope.isImage = function() { 
    ... 
    return true; 
} 

rootScope约束变量是随时随地访问你的应用程序中,这样你就不必让他们在你的控制器。

正确的,稍微复杂一点的方法是使用自定义指令。 我没有测试过这一点,但沿着线的东西:

angular.module('myApp').directive("isImage", function() { 
return { 
    restrict: 'E', 
    scope: { 
     src: '=src' 
    }, 
    link: function (scope, element, attrs) { 
     if (!isImage(scope.src)) { //your logic for deciding if it's an image here 
      element.hide(); 
     } 
    } 
}; 

});

,并在你的HTML:

<is-image src="myImage"></is-image> 
相关问题