Angular - 指令不起作用

时间:2015-06-18 07:09:33

标签: javascript angularjs

我是Angular的新手。不确定为什么指令在下面不起作用。搜索了一些文章。什么都没有帮助

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

4 个答案:

答案 0 :(得分:4)

应该是:

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

答案 1 :(得分:2)

您应该像这样更改$ watch:

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

演示:http://jsfiddle.net/vikashvverma/LzLe71ft/6/

答案 2 :(得分:1)

试试这个

&#13;
&#13;
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);
            });
        }
    }
}]);
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

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>

以下是工作模型JSFIDDLE LINK