javascript - 将参数从 View 传递到 Controller 再到 AngularJS 中的工厂

标签 javascript angularjs twitter-bootstrap

我对使用 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/

相关文章:

jquery - ASP.NET-MVC5 - 为什么 Bootstrap v4 主题不能正确显示组件?

javascript - 页面加载时的 JQuery 搜索

javascript - PHP 数组到 javascript 数组 UTF-8

javascript - Promises polyfill 是否在 Google Closure Compiler 20161024 中包含 all()?

jquery-plugins - Ember 数据日期绑定(bind)

jquery - Bootstrap - 修复了没有其余栏的可折叠导航栏按钮

JavaScript 使 AJAX 发布 onclick 事件,然后继续执行原始操作

javascript - Angular 路由漂亮 URL 错误

c# - WebAPI + AngularJS 中基于 DateTime 的动态 HTTP 请求

javascript - 如何添加第二条 JSON 消息?