vishalaksh
vishalaksh

Reputation: 2164

Directive not triggering on change of attibute

I have a 2 dropdowns from which user makes selection. And based on those values, the attributes are sent to directives and corresponding function should get called.

The problem is that the directives are not called on the change of value.

Here is the html code:

<div ng-controller=visCtrl> 

        <select ng-model="selectedDistrict" ng-options="item as item for item in districts  " ng-init="selectedDistrict='GUNTUR'"></select>
        <select ng-model="selectedYear" ng-init="selectedYear='2005'" ng-options="item as item.YEAR for item in opendata | filter:{ DISTRICT: selectedDistrict  }"></select>


        <div ng-repeat="item in categories">
            <div id="containervis-item" ng-init="init(item.value)" class="container col-sm-12">
                <div scatter-chart city-name={{selectedDistrict}} crime-name={{item}} current-year={{selectedYear}} vis-file=dataFile id="divVisScatter-{{item}}" class="divVis divVisScatter col-sm-6">
                    {{item}}
                </div>
                <div linear-chart city-name={{selectedDistrict}} crime-name={{item}} vis-file=dataFile  class="divVis divVisLine col-sm-6"></div>
            </div>
        </div>
    </div>

Here is the directive code:

myApp.directive('scatterChart', function($window){
    return{
        restrict:'EA',
        template:"<svg width='850' height='200'></svg>",
        link: function(scope, elem, attrs){

            var d3 = $window.d3;
            var rawSvg=elem.find('svg');
            var svg = d3.select(rawSvg[0]); 

            var cityName=attrs.cityName;
                var crime=attrs.crimeName;
                var year=attrs.currentYear;


                console.log(cityName);//doesnt get called when selection is made
                }
            };
        });

The the directive is called with initial values only. Also, upon making a selection, the DOM gets changed and the city-name and crime-name attributes get new value, but the function isnt called.

Upvotes: 0

Views: 33

Answers (1)

kasimoglou
kasimoglou

Reputation: 384

By 'the corresponding function should get called' you mean link function? Link function is executed once, after the compilation phase and it is the right place to attach event listeners to HTML template, etc. Check here for more details.

In case you want to execute a function everytime an attribute's value changes, you have to $watch it, and include all the necessary code into $watch function.
eg.

scope.$watch(function() {
     return attrs.cityName;
}, function(value) {
    console.log(value);
})

Upvotes: 1

Related Questions