javascript - 从另一个 Controller Angularjs 调用函数

标签 javascript angularjs

这是我的简单 Controller :

XApp.controller('LoadCountriesController', function ($scope, GetAllCountries, $http, $location) {
    console.log('Step 3');
    var Obj = new Object();
    Obj.SPNAME = "GetAllCountry";

    $scope.countryData = GetAllCountries.query({ parameters: Obj }, function () {
        $scope.countryList = $scope.countryData;
        console.log(JSON.stringify($scope.countryList));
    });

    $scope.$on('bindmsDropDown', function (ngRepeatFinishedEvent) {
        var CountryCode = "in";
        //Check whether the cookie is already set
        var cookiename = 'currency';
        if ($.cookie(cookiename)) {
            $("#countries").val($.cookie(cookiename));
            CountryCode = $.cookie(cookiename);
        }
        else {
            $("#countries").val('in');
            $.cookie('currency', $("#countries").val(), { expires: 365, path: '/' });
            CountryCode = $("#countries").val();
        }

        $("#countries").msDropdown();
    });
});


XApp.factory('GetAllCountries', function ($resource) {
    console.log('Step 4');
    return $resource('api/master/:object?type=json', {}, { 'query': { method: 'GET', isArray: true } });
});

我正在使用上面的 Controller 来填充下拉列表:

<div class="CountryDDL" data-ng-controller="LoadCountriesController">
<select name="countries" id="countries" style="width: 84px; display: block;">
<option on-finish-render="bindmsDropDown" data-ng-repeat="country in countryList" value="{{ country.CountryCode }}"   data-image="content/themes/msdropdown/icons/blank.gif" data-imagecss="flag {{ country.CountryCode }}" data-title="{{ country.CurrencyName }}" >{{ country.CurrencyCode }}</option></select></div>

我想在 select 的 onchange 事件上从另一个 Controller (ProductsController) 调用函数 (loadData)

var ProductsController = function ($scope, GetProductsForIndex, $http, $location) {
    console.log('Step 1');
    $scope.products = [];
    $scope.busy = false;
    var indexPageNo = 0;
    $scope.loadData = function () {
        if ($scope.busy) return;
        $scope.busy = true;

        indexPageNo += 1;
        var Obj = new Object();

        Obj.PAGEINDEX = indexPageNo;
        Obj.PAGESIZE = 20;
        Obj.SPNAME = "index_get_products";
        Obj.PAGECOUNT = null;
        Obj.COUNTRYCODE = 'in'
        $scope.data = GetProductsForIndex.query({ parameters: Obj }, function () {
            console.log(JSON.stringify($scope.data));
            for (var i = 0; i < $scope.data.length ; i++) {
                $scope.products.push($scope.data[i]);
            }
            $scope.busy = false;
        });
    }

    //$scope.loadData();
    $scope.$on('bindWookmarkHandler', function (ngRepeatFinishedEvent) {
        console.log("done");
        if (indexPageNo === 1) {
            executeOnFirstLoad();
        } else {
            var handler = null;
            var options = {
                autoResize: true, // This will auto-update the layout when the browser window is resized.
                container: $('#main'), // Optional, used for some extra CSS styling
                offset: 17, // Optional, the distance between grid items
                itemWidth: 225 // Optional, the width of a grid item 
            };

            if (handler) handler.wookmarkClear();
            // Create a new layout handler.
            handler = $('#tiles li');
            handler.wookmark(options);
        }

    });

};


XApp.factory('GetProductsForIndex', function ($resource) {
    console.log('Step 2');
    return $resource('api/index/:object?type=json', {}, { 'query': { method: 'GET', isArray: true } });
});

最佳答案

您可以在 AngularJS 中使用服务在 Controller 之间共享数据。看这个stackoverflow question了解更多信息。

这是一个示例:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);

// A service to share data between FirstCtrl and SecondCtrl
myApp.factory('Data', function(){
    return { FirstName: '' };
});

myApp.controller('FirstCtrl', function( $scope, Data ){
	$scope.Data = Data;
});

myApp.controller('SecondCtrl', function( $scope, Data ){
	$scope.Data = Data;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" style="width:500px;background:#d2d0d0; padding:10px 30px; margin:0 auto;">

		<div ng-controller="FirstCtrl">
    <b>First Controller</b><br/><br/>
			<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
			<br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
		</div>
		<hr>
    <b>Second Controller</b><br/><br/>
		<div ng-controller="SecondCtrl">
			Input should also be here: {{Data.FirstName}}<!-- Successfully updated it here too -->
		</div>

	</div>

关于javascript - 从另一个 Controller Angularjs 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602407/

相关文章:

javascript - 有没有办法使用 HTML 通过 gmail 发送电子邮件

javascript - p5 调整 Canvas 大小问题; resizeCanvas 未定义

javascript - 如何使用 MaterialDesign Lite 正确附加 TextField?

javascript - 如何使用一个参数调用多个变量的过滤器?

javascript - 具有计算列的 Angularjs x 可编辑表

javascript - 未捕获的 TypeError : FB. 登录不是函数

javascript - Laravel + jquery 对话框在发布后重定向(+fullcalendar)

php - 代码点火器 + Angular Js : How to receive JSON data

angularjs - 用于 MEAN 应用的 Yeoman 子生成器?

javascript - 找不到命名空间 'ng'