简体   繁体   中英

Pass parameter and ng-click to the angular directive

I want to pass some data from HTML to the directive, also this directive should be clickable by ng-click. Question is how i can pass parameter of link function to the template?

 app.directive("hello", function(){ return { restrict: "E", template : '<button ng-click="updateModel()">'+attrs.name+'</button>', scope : {}, link : function(scope, element, attrs, ctrl){ scope.updateModel = function(){ console.log("yay"); } } }; }); 

Here is HTML directive: <hello name="john"></hello>

Try this method

JS

app.directive("hello", function(){
      return {
        restrict: "E",
        template : '<button  ng-click="updateModel()" >{{name}}</button>',
        scope : {
            name :"@",
            user :"="
        },
        link : function(scope, element, attrs, ctrl){
          scope.updateModel = function(){
            console.log(scope.name, scope.user);
          }
        }
      };
    });

HTML

<hello name="jimbrooism" user="user"></hello>
  1. = is two-way binding
  2. @ simply reads the value (one-way binding)
  3. & is used to bind functions

look:

app.directive("hello", function(){
  return {
    restrict: "E",
    template : '<button  ng-click="updateModel()">{{name}}</button>',
    scope : {
      name: "@"
    },
    link : function(scope, element, attrs, ctrl){
      scope.updateModel = function(){
        console.log("yay");
      }
    }
  };
});

Plunker: http://plnkr.co/edit/da8eHrxaxZsZm731b0Uk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM