javascript - 仅调用一次 Controller 功能,两个 div 具有相同的 Controller

标签 javascript angularjs asp.net-mvc-3

我正在研究angularjs。我有两个 div 共享同一个 Controller 。我的 Controller 代码是。

var app=angular.module('categoryPageApp', []);
app.controller('NgProducts', function($scope,UpdateService) {

   $scope.orderby=5;
   $scope.pageNumber=1;
   $scope.loadProducts=function($scope){
             //here goes ajax call
     };

 });

我的两个具有相同 Controller 的 div 是

<div ng-app="categoryPageApp">
<div id="cat-products" ng-controller="NgProducts">
</div>
<div id="brand-filter" ng-controller="NgProducts">
</div>
</div>

正如我们所看到的,现在所有变量将被声明两次,并且更新函数将被调用。 我不希望这种情况发生,因为单次 http 调用就可以完成工作。有没有解决这个问题的方法。

我还想使用 Angular js 为我的产品构建分页器。任何帮助将不胜感激。

最佳答案

您可以尝试在加载产品后存储一些标志,如下所示:

app.controller('NgProducts', function($scope,UpdateService) {
   if (!$scope.productsAreLoaded)
     $scope.orderby=5;
     $scope.pageNumber=1;
     $scope.loadProducts=function($scope){
        //here goes ajax call
        $scope.productsAreLoaded = true;
     };

});

关于javascript - 仅调用一次 Controller 功能,两个 div 具有相同的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25945600/

相关文章:

javascript - CSS 和 jQuery 的宽度不同

javascript - NodeJS - 从数组中减去数组,而不是删除所有重复项

javascript - 如何使用 flexbox 对齐元素?

jquery - 可以使用 AngularUI jQuery PassThrough 作为 WayPoints 插件吗?

javascript - Browserify 为模块分配相对路径而不是绝对路径

javascript - 在js中提交表单时从响应正文中删除前缀

javascript - 在 angularjs 中使用 ng-repeat 时扩展 $index 的范围

asp.net-mvc - MVC3 : Use of ActionMethodSelectorAttribute causes HttpPostAttribute to be ignored

c# - 如何优雅地处理时区

asp.net-mvc - 将 id 从 View 传递给 Controller