Search code examples
javascriptangularjsangular-directiveangularjs-ng-change

How to execute ng-change after loading data on custom directive


I wrote a custom directive in angular js that is available in plnkr, when the directive is loaded it already calls the changed() function on MainCtrl, I need to stop changed() function until the data loads into the directive and after that, it should start to watch the changes on input which is inside the directive and BTW the changed() function should be in MainCtrl as it is in the example so is there any way to stop execution of ng-change before loading data into directive? here is the code:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = "someName";
  $scope.statusText = "unChanged";
  $scope.changed = function(){
          $scope.statusText = "changed";
      };
});


app.directive("myDirective", function () {
    return {
        restrict: 'EA',
        scope: {
            ngModel: "=",
            ngChange: "="
        },
        templateUrl: "template.html",
        link: function ($scope, elem, attrs) {



        }
    }
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

    <my-directive ng-model="name" ng-change="changed()"></my-directive>
    <p>{{statusText}}</p>

    <script type="text/ng-template" id="template.html">
      <input type="text" ng-model="ngModel" ng-change="ngChange" >
    </script>
  </body>

</html>

Solution

    • you have to change your directive's receive property ngModel and ngChange, it conflicts with angularhs's built in directives.
    • use '&' if you want to call function out of directive

    refer this plunker(I just forked from your question).