Create directives with Angularjs

Asked

Viewed 5,415 times

1

The button should display an Alert but nothing, no error appears. What error? Follow the code:

  angular.module('App', [])
                    .directive('sonclick', function () {    
                         return {
                             restrict: 'A',
                             link: function(scope,element,attrs){
                                 element.bind('click',function(){       
                                     scope.$eval(attrs.sonclick);
                                 })
                             }
                         };
                    })
                    .controller('CtrlApp', function ($scope) {
                          $scope.executa = function(){
                              alert("scope");           
                          };
                    });
<!DOCTYPE HTML>
<html ng-app="App">
    <head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js" type="text/javascript"></script>
    </head>
    <body>
        <div ng-controller="CtrlApp">
            <button son-click="executa()">clique aqui</button>

        </div>  
       
    </body>
</html>

  • What exactly are you trying to do?

1 answer

3


Changing the sonclick for sonClick (attention to the capital C) seems to solve the problem.

  angular.module('App', [])
                    .directive('sonClick', function () {    
                         return {
                             restrict: 'A',
                             link: function(scope,element,attrs){
                                 element.bind('click',function(){       
                                     scope.$eval(attrs.sonClick);
                                 })
                             }
                         };
                    })
                    .controller('CtrlApp', function ($scope) {
                          $scope.executa = function(){
                              alert("scope");           
                          };
                    });
<!DOCTYPE HTML>
<html ng-app="App">
    <head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js" type="text/javascript"></script>
    </head>
    <body>
        <div ng-controller="CtrlApp">
            <button son-click="executa()">clique aqui</button>

        </div>  
       
    </body>
</html>

  • So, briefly algo-algo of view would algoAlgo in the script of the directive? sta-ck > staCk? I’m dealing with Angularjs and did not know yet that it was possible to create my own directives.

  • 1

    @rrnan That’s right! In HTML you can use attributes like novo-item, novo:item and novo_item that the directive name in javascript will always be novoItem (camelCase).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.