0

I am trying to create an angular directive that will be able to get BOTH model object and a string.
if the directive get a string it just output HTML, but if it's a model the the directive will watch the model for changes and will output data respectively.

I had tried to use the next code:

App.directive('iso2symbol', function () {
    return {
        restrict: 'E',
        replace: true,
        link: function ($scope, $element, $attrs) {
            var curIsoObj = $scope.$eval($attrs.curIso);
            //this is object it may change
            if (typeof curIsoObj !== 'undefined') {
                console.log('not a text');
                $scope.$watch('curIso', function (value) {
                   console.log(value);
                });
            }
        },
        template: '<span>{{currencySymbol}}</span>'
    }
}]);

This is not working, I had googled it for long time and I don't find the problem....

here is a link to JSfiddle where I had set a DEMO

Wazime
  • 1,423
  • 1
  • 18
  • 26
  • Is this really the best way to tackle things? What if you come to a case where it's suppose to be a string but you have a model object with the same string? Your code will not interpret it as a string and it will not work properly then you will spend hours debugging it. – yangli-io Mar 03 '15 at 22:27
  • This directive should act as a filter... I can't use a filter here for [various reasons](http://stackoverflow.com/questions/28841486/is-there-a-way-to-update-filter-with-async-data), so I need it to accept any data type. – Wazime Mar 03 '15 at 22:30

2 Answers2

0

Becareful with what you're watching.

according to your watch function you're watching $scope.curIso which really isn't a scope object.

you should be watching

$scope.$watch(function(){return $scope.$eval($attrs.curIso);}, function (value) {
    $scope.txt = value;
});
yangli-io
  • 16,760
  • 8
  • 37
  • 47
  • Just beware you test the string version/model object version in the same controller since you're referring to $scope.txt which by changing it in one directive will change it in all other directives. – yangli-io Mar 03 '15 at 22:42
0

Try this:

App.directive('iso2symbol', function () {
    return {
        restrict: 'E',
        replace: true,
        require: 'ngModel',
        scope: {
            curIso: '='
        },
        link: function ($scope, $element, $attrs) {
            $scope.$observe('curIso', function(newValue, oldValue){
                var curIsoObj = newValue;
                // Do your test now to see if it's undefined,
                // a string, or generic object.
                // (the first time it will likely be undefined)
            }
        },
        template: '<span>{{currencySymbol}}</span>'
    }
}]);
HankScorpio
  • 3,612
  • 15
  • 27