无法更改呼叫另一个控制器

Can ng-change call another controller?

本文关键字:另一个 控制器 呼叫      更新时间:2024-06-19

我有以下html

<div ng-controller="select">        
    <select ng-options="n for n in names" 
    ng-model="selected.item"
    ng-change="change()">
    </select>
</div>
<div ng-controller="graph">
    <input type="text" ng-model="mySelected.item">
    <canvas id="line" class="chart chart-line" chart-labels="gs" chart-data="ser">
    </canvas>
</div>

我希望ng选项中的change()方法调用"graph"控制器。基本上,如果更改了选项,则应该更新图形。有办法吗?请帮忙。

如果需要,我还会分享我的控制器代码:`

app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.mySelected = myService.selected;
console.log($scope.mySelected);
//$http.get('/myapp/stocklist/'+ $scope.mySelected).
$http.get('/myapp/stocklist/AMZN').
success(function(data) {
gs = [];
ser = [];    
for( var i=0; i<data.length; i++ ) {
    gs.push(data[i].name);
    ser.push(data[i].high);
}
$scope.gs=gs;    
$scope.ser=[];
$scope.ser.push(ser);
});
}]);
app.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.selected = myService.selected;
$http.get('/myapp/stocknames').
success(function(data) {
    $scope.names=data;
    console.log($scope.names);          
});
}]);

在图形控制器中,您将使用$on:

    scope.$on('onServiceSelected', function (event, selectedService) {
           $scope.mySelected = selectedService;
    });

在你的另一个控制器中,你会使用$broadcast:

  $rootScope.$broadcast('onServiceSelected',$scope.serviceSelection);

这应该为你指明正确的方向。