0

Use ng-if in Angularjs Directive

I have a showTaskDetailView$ stream that I can subscribe to and I can push a boolean value through it.

angular.module('Project').directive('something', () => {
    return {
        restrict: 'E',
        template: '<div>something: {{toggleValue}}</div>',
        replace: true,
        link() {
            something();
            function something() {
                showTaskDetailView$.subscribe(value => {
                    let toggleValue = value;
                    console.log(toggleValue);
                });
            }
        }
    };
});

When I run this directive and I change the showTaskDetailView$ value I see the new value in my console.log. But nothing is happening in the DOM.

4
  • Because toggleValue is a local variable inside the context of the subscribe callback. Commented May 24, 2019 at 19:30
  • Okay that makes sense. Any suggestions how to make the toggleValue available outside subscribe? Commented May 24, 2019 at 19:36
  • Use a component with a controller. See AngularJS Developer Guide - components. Commented May 24, 2019 at 20:57
  • I see that you have 29 Angular 2+ questions. Is it possible you are trying to solve an Angular 2+ problem? The example in your question is AngularJS. AngularJS directives and components do not work with Angular 2+. Commented May 24, 2019 at 21:10

1 Answer 1

0

Your toggleValue is a local variable and not binded to $scope. For DOM to update you need to add toggelValue on $scope.

Change your link function to:

link(scope) {
        something();
        function something() {
            showTaskDetailView$.subscribe(value => {
                scope.toggleValue = value; <-------------
                console.log(scope.toggleValue);
            });
        }
    }

Now you should see the updated DOM. Read more here:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.