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

前端 未结 5 779
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 20:09

I have a directive with isolated scope with a value with two way binding to the parent scope. I am calling a method that changes the value in the parent scope, but the chang

5条回答
  •  自闭症患者
    2020-12-08 20:31

    The answer Use $scope.$apply() is completely incorrect.

    The only way that I have seen to update the scope in your directive is like this:

    angular.module('app')
    .directive('navbar', function () {
        return {
            templateUrl: '../../views/navbar.html',
            replace: 'true',
            restrict: 'E',
            scope: {
                email: '='
            },
            link: function (scope, elem, attrs) {
                scope.$on('userLoggedIn', function (event, args) {
                    scope.email = args.email;
                });
                scope.$on('userLoggedOut', function (event) {
                    scope.email = false;
                    console.log(newValue);
    
                });
    
            }
        }
    });
    

    and emitting your events in the controller like this:

    $rootScope.$broadcast('userLoggedIn', user);
    

    This feels like such a hack I hope the angular gurus can see this post and provide a better answer, but as it is the accepted answer does not even work and just gives the error $digest already in progress

提交回复
热议问题