0

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;
                 ...
                 ...

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

first if i change it to "=" i will have to pass object not string and remove the http get and play with the passed object. For now i want to play with the string which represents string URL. Thanks for answer ill check this attr.observe
change to = only requires your template to change annotation-url="annotatonData" and you still access $scope.annotationUrl inside your directive
thanks it worked so basically i wrapped everything inside InIt function which i invoke it inside the watch with new value passed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.