2015-07-21 85 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; 
     } 
    }); 
} 
相關問題