The directive view is not updated when updating the scope variable in the message

I cannot update my view by updating the scope variable in the post link function.

Below is my directive.

    <my-directive color='purple'>
    </my-directive>

The following is the definition of my directive.

app.directive('myDirective', function () {
    console.log('My Directive Called');
    return {
        restrict: 'E',
        scope: {
            localVar: '@color'
        },
        //template: '<span></span>', // When I enable this template it works fine.
        /* This link way it is working fine.
        link: function (scope, iElement, iAttrs) {
            console.log(iElement);
            iAttrs.color = 'red';
        }*/
        //This is not working Reason don't know.
        compile: function (tElement, tAttrs) {
            var spanElem = angular.element('<span> {{ localVar }} </span>');
            spanElem.attr('color', tAttrs.color);

            tElement.replaceWith(spanElem);

            return function (scope, iElement, iAttrs) {
                iAttrs.color = 'red';
            };
        } 
    };
});

I want to know the reason why this code does not work. It will work if I specify the template property in the directive definition object. But I want to know what happens in the code above. Please help me.

+4
source share
2 answers

This is very easy if you do something like this:

Jsfiddle

angular.module('myApp', [])
.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
            localVar: '@color'
        },
        template: '<span> {{ localVar }} </span>'
    };
});
+1
source

Without calling the communication function, there is no two-way data binding between the template created by the compilation function and the scope.

, link, .

angular docs. , .

HTML :

$ DOM .

  • , , , DOM. .

  • , DOM, , .

    . DOM. . "" , .

  • $compile , . , , , ​​ $watchs , .

DOM. , DOM.



EDIT CODE:

compile link,



EDIT CODE 2:

.directive('myDirective', function () {
    console.log('My Directive Called');
    return {
        restrict: 'E',
        scope: {
            localVar: '@color'
        },
        template : '<span> {{ localVar }} </span>'
    };
});



HTML:

<my-directive color='purple'>
    </my-directive>

3:

directive('myDirective', function () {
    console.log('My Directive Called');
    return {
        restrict: 'EA', 
        template: '<span>{{ localVar }}</span>', // When I enable this template it works fine.

        compile: function (tElement, tAttrs) {
            return {
                post: function postLink(scope, iElement, iAttrs, controller) { 
                    scope.localVar = 'red';
                }
            }


        } 
    };
})
+1

All Articles