繁体   English   中英

在AngularJS中将参数从视图传递到控制器到工厂

[英]Passing parameter from view to controller to factory in AngularJS

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

“品牌”选项卡已创建,但是未创建模型列表。 我正在尝试使用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值。 我在这里做错了什么?

加载控制器后,将调用$scope.init getModels($scope.brandId)调用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)"

在视图上使用:

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;
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM