http://jsfiddle.net/p8RNJ/3/

当我按下“提交”按钮时, fooController 控制器中的等于“A”,所以 barController 获取分配值“A”,该值在 UI 中得到确认:

bar in controller: A

当我按下“设置值”按钮后, fooController 通过与值“B”绑定从指令更新,这在 UI 中得到确认:

foo in controller: B

然而,当我按下“提交”按钮后, fooController 控制器中仍然具有旧值“A”,因此 $scope.barController 再次被赋予值“A”:

bar in controller: A

我怎样才能确保在第二次提交时 fooController 具有正确的“B”值并且 barController 也被分配了值“B”?

HTML:

<div ng-app="app" ng-controller="Controller">
<script type="text/ng-template" id="directive-template.html">
    foo in directive: {{fooDirective}}<br/>
    <button ng-click="setValue()">set value</button>
</script>

<form data-ng-submit="getModel()">
    <div ng-controller="Controller">
        <button type="submit">submit</button><br/>
        foo in controller: {{fooController}}<br/>
        bar in controller: {{barController}}<br/>
        <my-customer model="fooController"></my-customer>
    </div>
</form>
</div>

还有JS:

angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {
    $scope.fooController = 'A';
    $scope.getModel = function() {
        $scope.barController = $scope.fooController;
    }
}])

.directive('myCustomer', function() {
    return {
        restrict: 'E',
        scope: {
            fooDirective: '=model'
        },
        controller: function ($scope) {
            $scope.setValue = function() {
                $scope.fooDirective = 'B';
            };
        },
        templateUrl: 'directive-template.html'
    };
});
有帮助吗?

解决方案

不要使用原始数据类型(数字、字符串、布尔值),因为继承不能双向工作,它只能从父 $scope 到子 $scope 工作。如果您希望它以用户对象或数组的方式工作(这就是角度社区实际推荐的)。

$scope.barController = "aaaa";

应该:

$scope.modelState.barController = "aaa";

这样,如果您从子范围更改它,它也会在父范围中更新。

其他提示

您需要将指令更改包装在 $scope.apply 中

  $scope.apply(function(){
        $scope.setValue = function() {
            $scope.fooDirective = 'B';
        };
   }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top