可以更换另一个控制器吗?

时间:2016-04-13 20:28:17

标签: javascript angularjs

我有以下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-option中的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);          
});
}]);

1 个答案:

答案 0 :(得分:0)

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

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

在您的其他控制器中,您将使用$ broadcast:

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

这应该指向正确的方向。