如何在另一个控制器中调用一个控制器阵列

时间:2015-08-23 16:03:33

标签: angularjs

我创建了countryApp模块。我在aboutCtrl中创建了“names”数组。

我想在insertContact函数中访问contactCtrl中的“names”数组。

{{1}}

2 个答案:

答案 0 :(得分:0)

扩展Claies'实际代码的解决方案:

countryApp.controller('aboutCtrl', function($scope, dataService) {

    /* If you're binding the values into your HTML,
    you need to $watch the service variable 'names' */

    $scope.$watch(function() { return dataService.names }, function() {
        $scope.names = dataService.names;
    });

    dataService.names = [{name:'venu',number:'22222',sex:'male'},{name:'Aishu',number:'1111',sex:'female'},{name:'Milky',number:'2222',sex:'female'}]

});

countryApp.controller('contactCtrl', function($scope, dataService) {

    /* You can place the same watch as in aboutCtrl here if
    you're displaying stuff in HTML that's related to this controller */

        $scope.greeting = 'Hello, World!';
      $scope.insertContact = function () {

         alert(dataService.names);

     }
     $scope.resetContact = function () {

     }
});

countryApp.service('dataService', function() {
    var dataObj = {};

    dataobj.names = [];

    return dataObj;
});

请注意有关$watch服务变量的评论;如果您想通过$scope变量在视图中显示值,则需要$watch相应的服务变量或$scope变量不会更新当服务变量的值改变时。

答案 1 :(得分:0)

如果您想在两个控制器之间进行通信,请参考以下小提琴:

Fiddlehttp://jsfiddle.net/VaibhavP17/nky45/

它显示了如何在两个控制器之间进行通信以及事件的细微差别。我希望这会有所帮助:)