AngularJS:父范围在指令(带隔离范围)中不更新双向绑定

前端之家收集整理的这篇文章主要介绍了AngularJS:父范围在指令(带隔离范围)中不更新双向绑定前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有隔离范围的指令,其值与双向绑定到父范围。我正在调用一个方法来更改父范围中的值,但更改不会在我的指令中应用(双向绑定不被触发)。这个问题非常相似:

AngularJS: Parent scope not updated in directive (with isolated scope) two way binding

但是我没有改变该指令的值,而是仅在父范围内进行更改。我阅读了解决方案,并在第五点说:

The watch() created by the isolated scope checks whether it's value for the bi-directional binding is in sync with the parent's value. If it isn't  the parent's value is copied to the isolated scope.

这意味着当我的父值更改为2时,会触发手表。它检查父值和指令值是否相同 – 如果不是,它将复制到指令值。好的,但是我的指令值仍然是1 …我失踪了什么?

html:

<div data-ng-app="testApp">
    <div data-ng-controller="testCtrl">
        <strong>{{myValue}}</strong>
        <span data-test-directive data-parent-item="myValue" 
            data-parent-update="update()"></span>
    </div>
</div>

JS:

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

testApp.directive('testDirective',function ($timeout) {
    return {
        scope: {
            key: '=parentItem',parentUpdate: '&'
        },replace: true,template:
            '<button data-ng-click="lock()">Lock</button>' +
            '</div>',controller: function ($scope,$element,$attrs) {
            $scope.lock = function () {
                console.log('directive :',$scope.key);

                 $scope.parentUpdate();
                 //$timeout($scope.parentUpdate); // would work.

                 // expecting the value to be 2,but it is 1
                 console.log('directive :',$scope.key);
            };
        }
    };
});

testApp.controller('testCtrl',function ($scope) {
    $scope.myValue = '1';
    $scope.update = function () {
        // Expecting local variable k,or $scope.pkey to have been
        // updated by calls in the directive's scope.
        console.log('CTRL:',$scope.myValue);
        $scope.myValue = "2";
        console.log('CTRL:',$scope.myValue);
    };
});

小提琴:http://jsfiddle.net/u69PT/17/

@H_404_20@
在您的控制器中更改$ scope.myValue后,使用$ scope。$ apply(),如:
testApp.controller('testCtrl',$scope.myValue);
        $scope.myValue = "2";
        $scope.$apply();
        console.log('CTRL:',$scope.myValue);
    };
});

猜你在找的Angularjs相关文章