Search code examples
angularjsangularjs-directiveangularjs-scope

Change text value when button is pressed with directives in angular


Here's my fiddle

I basically want to be able to change the text when a button is pressed. I have tried with both $observe and $watch inside link, but I still don't manage to get it working.

Code:

(function(){

    angular.module('app', [])


    .directive('testDirective', function(){
        return {
            restrict: 'E',
            scope: {
                title: '@'
            },
            template: '<div>this is a {{ title }}</div>',
            link: function(scope, element, attrs) {
                //?
            }
        };
    });

})()

Solution

  • You need to pass data as scope variable, you should not pass it as a string if you want to track changes.

    check this fiddle, replace counter data with your desired data. Hope this helps

    <div ng-controller='myctrl'>
        <test-directive title="counter"></test-directive>
        <hr></hr>
        <button type="button" ng-click = 'onclickbutton()'>Change names</button>
    </div>
    

    (function(){      
    
        angular.module('app', [])
        .controller('myctrl',function($scope){
            $scope.counter = 0;
            $scope.onclickbutton = function(){
               $scope.counter++;             
            }        
        })
    
        .directive('testDirective', function(){
            return {
                restrict: 'E',
                scope: {
                    title: '='
                },
                template: '<div>this is a {{ title }}</div>',
                link: function(scope, element, attrs) {
    
                }
            };
        });
    
    })();