2015-02-08 32 views
0

我有一个BaseController与我的所有其他控制器继承的常见功能。我怎样才能通过范围在角js模板

控制器是这样

function BaseController() { 

    this.defaultFilters = {}; 

    this.doStuff = function ($scope) { 
     $scope.myobj.value = 1; 
     this.otherfunction(); 
    }; 

我继承我的控制器这样

BaseController.call($scope);

现在我做的东西的功能,我需要通过$范围,因为MyObj中才可见那里。

现在我想知道我怎么可以通过在我的模板,因为我想调用该函数时,一些按钮一些点击,你与你的控制器的范围关联

ng-click="doStuff(scope)"

回答

1

一切,所以你只需将你的范围与一些变量联系起来,我想这将会完成这项工作。

事情是这样的:

app.controller(function($scope) { 
     $scope.scope = $scope; 

    }); 

但是,如果你通过一些标准的方法去,我建议把一些服务中,这些常用的功能,注射这种服务到每个控制器和视图中使用它。

事情是这样的:

app.service("constantService", function() { 

     this.data = {}; // This will represent your common data. 

     this.commonFunction = function() { 

     }; 

    }); 


    app.controller(function() { 
     $scope.constantService = constantService; 


     // You can now use $scope.constantService.data as your reference for data, and then can copy it to some local $scope variable whenever required. 
    }); 


    ng-click="constantService.commonFunction()" 
+0

感谢。假设如果我使用服务,那么在我需要修改该函数中的$ scope变量的情况下该怎么办。我无法在服务中做到这一点 – user3214546 2015-02-09 03:53:37

+0

如果您将数据存储在服务中,为什么要这么做呢?请参阅我的建议是将相关数据以及服务中的常用代码移动到全局可访问的位置,并在一个地方对其进行修改,从而随时随地修改它们。 – 2015-02-09 03:55:14

+0

感谢您的支持,其实我一直都在抱怨如何把所有的东西放在服务中,但我还没有找到最好的实践的例子,从互联网,有人已经表明如何做所有的服务东西。你知道任何在线链接,以便我可以看到人们如何在服务中投放东西 – user3214546 2015-02-09 04:34:48