我对使用 Bootstrap 的 AngularJS 还很陌生。 我有以下 HTML:
<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>
已创建 BRAND 选项卡,但未创建模型列表。我正在尝试使用 ng-init 将品牌 ID 传递到模型 Controller 中。
我的模型 Controller 看起来像:
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 值未定义。我在这里做错了什么?
最佳答案
您的$scope.init
正在您的 Controller 加载后被调用。将 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)"
被执行。
关于javascript - 将参数从 View 传递到 Controller 再到 AngularJS 中的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531228/