Georgi Antonov Georgi Antonov - 1 month ago 6
AngularJS Question

Dynamically change custom directive attribute value which should change directive content

Basically I have made custom directive to which i pass Url as string then inside the directive controller i'm calling

http.get()
method which creates the content inside this directive. What i want is to be able to change the value of
annotation-url
attribute which in return will change the content inside the directive because the new Url will return different
JSON
object. But it seems the directive is not getting refreshed when i change the
annotationData
from the controller.

HTML

<span ng-click="annotatonData = 'data/annotations1.json'">John</span>

<span ng-click="annotatonData = 'data/annotations2.json'">Marry</span>

<ng-annotate user-options="user" annotation-url="{{annotatonData}}"></ng-annotate>


Controller:

app.controller('ngAnnotationsController', ['$scope', '$http', function ($scope, $http) {

//InIt default http get

$scope.annotatonData = 'data/annotations1.json';

}]);


Directive:

app.directive('ngAnnotate', function () {
return {
templateUrl: 'templates/...',
restrict: 'E',
scope: {
annotationUrl: "@"

},
controller: ['$scope', '$http', function ($scope, $http) {

$http.get($scope.annotationUrl).then(function (response) {
$scope.data = response.data;
...
...

Answer

First, I suggest you change to

scope: {
    annotationUrl: "="
}

the you can add a watcher to invoke $http whenever value is changed

$scope.$watch('annotationUrl', function(newVal, oldVal) {
    if (newVal != oldVal) {
       $http.get(newVal).then(function (response) {
            $scope.data = response.data;
             ...
             ...
    }
}

However, if you want to keep annotationUrl as it is, you need to use $attr.$observe('annotationUrl', fn) to catch value changes.

Comments