user944513
user944513

Reputation: 12729

how to make custom directive in angular?

I am trying to make custom directive in angular .I try to add input field in my view when I click on button .In other words I am trying to make one custom directive in which when user press the button it add one input field in the browser .I think it is too easy if I am not use custom directive Mean If I use only controller then I take one array and push item in array when user click on button and button click is present on controller.

But when need to make custom directive where I will write my button click event in controller or directive

here is my code http://play.ionic.io/app/23ec466dac1d

   angular.module('app', ['ionic']).controller('appcontrl',function($scope){

  $scope.data=[]
}).directive('inputbutton',function(){
  return {

    restrict :'E',
    scope:{
      data:'='
    },
    template:'<button>Add input</button> <div ng-repeat="d in data"><input type="text"></div>',
    link:function(s,e,a){
      e.bind('click',function(){
        s.data.push({})
      })

    }

  }

})

I just need to add input field when user click on button using custom directive ..could you please tell me where i am doing wrong ?

can we make button template and click event inside the directive

Upvotes: 0

Views: 140

Answers (2)

Ashot
Ashot

Reputation: 1300

Here is a basic example for your logic .

  var TestApp = angular.module('App', []);

// controller

TestApp.controller('mainCtrl', function mainCtrl($scope) {
   $scope.data = [];
   $scope.addDataItem = function () {
   $scope.data.push({
        someFilield: 'some value'
    });
    console.log('pushing value ... ');
   }
});

// view

 <div ng-app="App" class="container" ng-controller="mainCtrl">
   <button type="button" ng-click="addDataItem()">Add an input</button>
   <div ng-repeat="d in data track by $index">
     <custom-directive model="d"></custom-directive>
   </div>
 </div>

// directive

  TestApp.directive('customDirective', function customDirective() {
    return {
      restrict: 'E',
      scope: {
        model: '='
      },
      template: 'item -> <input type = "text" />',
      link: function (scope, elem, attrs) {
        console.log('scope.model', scope.model);
      },
      controller: function ($scope) {
        // do staff here
      }
   }
 });

Upvotes: 0

ste2425
ste2425

Reputation: 4766

The reason it doesn't work is because your registering your click handler with jQuery. So when the click handler fires it is out of the scope of angular so angular does not know it needs to update its bindings.

So you have two options, the first is to tell angular in the click handler, 'yo buddy, update your bindings'. this is done using $scope.$apply

$apply docs: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

        e.bind('click',function(){
            s.$apply(function() {
                s.data.push({});
            });
        });

However angular already has built in directive for handling things like mouse clicks you can just use that and let angular do the work for you. This would be the better option.

so first in your view register a click handler on your button

<button ng-click="add()">Add input</button> <div ng-repeat="d in data"><input type="text"></div>

Then in your link simply add the add() method of your scope

        s.add = function () {
            s.data.push({});
        }

Heres a working fiddle showing both examples. http://jsfiddle.net/3dgdrvkq/


EDIT: Also noticed a slight bug in your initial click handler. You registering a click but not specifying the button to apply it to. So if you clicked anywhere in the directive, not just the button, the handler would fire. You should be more specific when registering events manually, using ids, class names attributes etc.

The e or element property of the link function is a jqlite or full jQuery object of the entire directive. If you have jQuery included before angular it will be a full jQuery object. If not it will a jqlite object. A thinned out version of jQuery.

Upvotes: 1

Related Questions