Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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.my@R_616_7548@;
        $scope.myValue = "2";
        console.log('CTRL:',$scope.my@R_616_7548@;
    };
});

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

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

大佬总结

以上是大佬教程为你收集整理的AngularJS:父范围在指令(带隔离范围)中不更新双向绑定全部内容,希望文章能够帮你解决AngularJS:父范围在指令(带隔离范围)中不更新双向绑定所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。