geeks geeks - 1 year ago 84
AngularJS Question

How to use ng-change function in directive?

I am trying to make auto-complete, for this I am using tags-input. Directive name is my-directive, Inside controller I am trying to call

function, but it is not working.

In auto-complete, you have to type 4 letters, like: john, then I will show options..


<body ng-app="myApp" ng-controller="appCtrl">
<my-directive apipoint="customerApi" modeldisplay="tags.selected" ng-model="tags.selected" change="selectUser(tags.selected)"></my-directive>


app.controller("appCtrl", function($scope){
$scope.tags = {};
$scope.tags.selected = [];
$scope.customerApi = ['tags.json'];
$scope.selectUser = function(foo) {
$scope.aux = foo;


app.directive("myDirective", ['$http',function($http){
return {
restrict: "E",
template : 'Here Use tag-input: <tags-input ng-model="modeldisplay"'+
'<auto-complete source="loadTags($query)"></auto-complete>'+
require: 'ngModel',
scope : {
modeldisplay: "=",
apipoint: "="
link : function(scope, element, attrs, ctrl){
scope.loadTags = function(query) {
return $http.get(scope.apipoint[0]);
scope.change = function(item){

**DEMO/Now Working **

Plunker Demo

One more thing Is my approach I right?, Reason Behind is that, In Angularjs View, I want to use auto-complete directive oneline, I want to make it as generic approach...

Answer Source

Some changes you should do to run the controller function.

Here is the working plunker Plunker

  1. You were using third party directive that doesn't provide ng-change on that. Yes but it provides on-tag-added="change1(modeldisplay). So ng-change was not working.

  2. You have passed function in the change attribute of you my-directive and again there was another change function in your directive scope, that was creating misunderstanding.

  3. You were accessing passed function using scope but you have not mentioned that in directive isolated scope. That's why that passed function was not accessible in directive scope.