2015-07-21 52 views
1

我对使用引导程序的AngularJS相当陌生。 我有以下HTML:将参数从视图传递到控制器到AngularJS的工厂

<div ng-controller="BrandCompanyController"> 
    <tabset> 
     <tab ng-repeat="brand in brands" heading="{{brand.Name}}" active="brand.active" disable="brand.Disabled"> 
      <div ng-controller="ModelController" ng-init="init(brand.ID)"> 

       <accordion> 
        <accordion-group heading="{{model.model_name}}" ng-repeat="model in models"> 
         INSERT DATA HERE 
        </accordion-group> 
       </accordion> 


      </div> 

     </tab> 

    </tabset> 
</div> 

创建选项卡品牌,但是,不创建模型的列表。我试图使用ng-init将品牌ID传递给模型控制器。

我ModelController样子:

myApp.controller('ModelController', ['$scope', 'ModelFactory', 
    function ($scope, ModelFactory) { 


     $scope.init = function(id) 
     { 
      $scope.brandId = id; 
      console.log("Inside Init: " + $scope.brandId); 

     } 

     console.log("Outside Init: " + $scope.brandId); 


     getModels($scope.brandId); 

     function getModels(brandId) { 

      ModelFactory.GetModels(brandId) 
       .success(function (mdls) { 
        $scope.models = mdls; 
        console.log($scope.mdls); 
       }) 
       .error(function (error) { 
        $scope.status = 'Unable to load model data: ' + error.message; 
        console.log($scope.status); 
       }); 
     } 
    }]); 

和我厂:

myApp.factory('ModelFactory', ['$http', function ($http) { 

    var ModelFactory = {}; 
    ModelFactory.GetModels = function (id) { 

      return $http({ 
      method: 'GET', 
      url: '/models/GetModels', 
      params: { brandId: id } 
     }); 
    }; 

    return ModelFactory; 

}]); 

在ModelController的$ scope.init设置$ scope.brandId。紧接着,在调用GetModels之前,$ scope.brandId值是未定义的。我在这里做错了什么?

回答

2

您的$scope.init在之后被称为您的控制器已加载。移动getModels($scope.brandId)调用该函数内部:

$scope.init = function(id) { 
    $scope.brandId = id; 
    console.log("Inside Init: " + $scope.brandId); 
    getModels(id); 
} 

这是因为第一,JS被加载并运行。 $scope.init被定义,调用console.log("Outside Init: " + $scope.brandId);,调用getModels函数。
然后,HTML完成加载。那个时候,执行ng-init="init(brand.ID)"

0

使用此上的观点:

ng-click="functionName(model.id)" 

对于控制器使用方法:

$scope.functionName = function(id) { 
    restservice.post('', "api/v1/.../?id=" +id).then(function(response) { 
     if (response != null && response.success) { 
      $scope.responseMessage = response.message; 
     } 
    }); 
} 
相关问题