ipradhansk
ipradhansk

Reputation: 352

Angular - Directive not working

I am new to Angular. Not sure why directive is not working below. Searched some articles. Nothing helps

angular.module('oneApp', []).controller('OneAppController', function($scope){
    //Some Logic
}).directive('dvReplaceText', ['$interval', '$compile', function($interval, $compile) {
    return {
    restrict: 'A',
    link: function(scope, element, attr) {
            scope.$watch(scope.data, function(value) {
                element.html(value);
            });
        }
    }
}]);

HTML:

<body ng-app="oneApp">
    <div ng-controller="OneAppController">
        <input class="input-data-box" ng-model="data" dv-replace-text=""/>
    </div>
</body>

JSFiddle Link

Upvotes: 1

Views: 598

Answers (4)

PavanAsTechie
PavanAsTechie

Reputation: 322

var app=angular.module('myApp', []);
app.controller('OneAppController', function($scope){
        //Some Logic
    console.log("data loaded");
    });


app.directive('dvReplaceText', function() {
      return {
        link: function(scope, element, attr) {
                scope.$watch(scope.data, function(value) {
                    element.html(value);
                });
            }
        }
});

HTML

<div ng-controller="OneAppController">
    <input class="input-data-box" ng-model="data" dv-replace-text/>
</div>

Here is the working model JSFIDDLE LINK

Upvotes: 1

Vikash
Vikash

Reputation: 1139

You should change $watch like this :

scope.$watch('data', function(value) {
                element.html(value);
                console.log(value);
            });

Demo : http://jsfiddle.net/vikashvverma/LzLe71ft/6/

Upvotes: 2

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

angular.module('oneApp', []).controller('OneAppController', function($scope){
 
    //Some Logic
}).directive('dvReplaceText', ['$interval', '$compile', function($interval, $compile) {
    return {
    restrict: 'A',
    link: function(scope, element, attr) {
            scope.$watch("data", function(value) {
                //element.value(value);
              console.log(value);
            });
        }
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="oneApp">
    <div ng-controller="OneAppController">
        <input class="input-data-box" ng-model="data" dv-replace-text=""/>
    </div>
</body>

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52837

Should be:

scope.$watch('data', function(value) {
   ...
});

Upvotes: 4

Related Questions