跨共享控制器上的部分视图的操作未触发

时间:2015-01-13 20:39:23

标签: angularjs single-responsibility-principle

我有几个可重用的代码,我试图分开。我遇到的问题是两个是直接相关的,但是在页面的不同部分,我希望它们在单独的局部视图中,所以我有两个部分视图共享相同的角度控制器。

HTML: 部分观点1:

<div ng-controller="CustomerController" data-ng-init="init()">
<div class="col-md-2 col-md-offset-5" style="outline: 1px solid black; margin-top: 1%">
    <div class="text-center">
        <div class="radio-inline" ng-repeat="customerOption in customerOptions">
            <input type="radio" id="{{customerOption.Value}}" name="customer" ng-change="getCustomers(customerType)" ng-model="customerType" ng-value="customerOption.Key" ng-checked="customerOption.Checked" />{{customerOption.Value}}
        </div>
    </div>
</div>

部分视图2:

<div ng-controller="CustomerController" data-ng-init="init()" class="col-md-2">
<select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>

</div>

角度控制器:

var customer = angular.module('customer', []);

 customer.controller('CustomerController', [
"$scope", "customerService",
function ($scope, customerService) {
    $scope.customerOptions = CustomerOptions;

    $scope.getCustomers = function (customerType) {
        $scope.showContent = false;
        if (customerType == "1") {
            customerService.getProduction().then(function (result) { $scope.customers = result.data; });
        } else if (customerType == "2") {
            customerService.getTest().then(function (result) { $scope.customers = result.data; });
        } else {
            customerService.getAll().then(function (result) { $scope.customers = result.data; });
        }
    };

    $scope.init = function() {
        $scope.getCustomers("3");
    }
}
])

当我更改部分视图1上的单选按钮时,它会触发getCustomer()方法,但它不会将列表更改为更新列表..

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的控制器正在创建两个彼此独立的实例,因此他们不了解彼此。你可以:

使用服务/工厂在控制器之间保留数据,或

将父控制器放在两个部分的容器元素上,这样它们都可以访问同一个控制器。