ngModel在自定义指令中不起作用

时间:2014-07-11 06:31:29

标签: angularjs

我知道肯定是问题我没有理解AngularJs的范围。我不得不承诺这对我来说很难。所以我在这里发布一个例子,希望有人帮我把它弄清楚。感谢。

Html部分

<test-Area ng-model="testModel.text"></test-Area>
<input type="text" ng-model="testModel.text"></input>
<textarea ng-model="testModel.text"></textarea>

JS部分

app.controller('AppController', function ($scope, $log) {
    $scope.testModel={text:"123"};
})

app.directive('testArea',function() {
    var textareaInputDir = {};
    textareaInputDir.restrict="E";
    textareaInputDir.replace="true";
    textareaInputDir.template="<div><textarea ></textarea><label><small></small><span >*</span></label></div>";
    textareaInputDir.require="ngModel";
    textareaInputDir.link=function (scope, jqElement, attrs,ngModelCtrl) {
        scope.backgroundValue={text:''};
        ngModelCtrl.$render = function () {
            jqElement.find('textarea').text(ngModelCtrl.$viewValue);
            scope.backgroundValue.text=ngModelCtrl.$viewValue;
        }
        //get the textarea element
        var txtAreaElement = jqElement.find('textarea');
        //listen for the change event

        txtAreaElement.bind('keyup', function(){
            if (scope.$$phase) return;
            scope.$apply(function () {
                var bgVal=angular.isString(ngModelCtrl.$viewValue) ? ngModelCtrl.$viewValue : '';
                scope.backgroundValue.text=bgVal;
                ngModelCtrl.$setViewValue(bgVal);
            });

        });
        scope.$watch('backgroundValue.text',function()
        {
            ngModelCtrl.$setViewValue(scope.backgroundValue.text)
        });
    };
    return textareaInputDir;
});

请在fiddle中查看我到目前为止所做的工作。

我试图为我的指令testArea和其他人实现两种方式绑定。但我无法弄清楚为什么它在我的指令中不起作用?

更新

我稍微更改了代码。但仍然有问题。如果我改变了文本区域的值。两种方式的约束将会丢失......

txtAreaElement.bind('keyup', function(){
            if (scope.$$phase) return;
            scope.$apply(function () {
                var txtAreaElement = jqElement.find('textarea');        
                var bgVal=txtAreaElement[0].value;
                scope.backgroundValue.text=bgVal;
                ngModelCtrl.$setViewValue(bgVal);

            });

        });

2 个答案:

答案 0 :(得分:2)

您必须设置ng-model不在您的指令上,您需要在textarea元素上设置

check example

以您的方式申请以<div>开头的指令模板元素。

答案 1 :(得分:1)

我发现是否要应用双向绑定。它不需要使用NgModelController。根据{{​​3}}。

请在下面查看。

<强> HTML

<test-Area ng-model="testModel.text"></test-Area>

<强> JS

app.directive('testArea',function() {
    var textareaInputDir = {};
    textareaInputDir.restrict="E";
    textareaInputDir.replace="true";
    textareaInputDir.scope={ngModel:'='};
    textareaInputDir.template="<div><textarea ng-model='ngModel'></textarea><label><small></small><span >*</span></label></div>";

    return textareaInputDir;
});

如果出现问题。请帮助纠正我。谢谢。

相关问题