2014-04-07 164 views
1

这是我的场景。我正在使用javascript动态添加一段代码。由于它的动态,我必须将它绑定到我的angularjs范围,这是完成的。但我在这里有一个问题。文本框中有一个指令适用于它。但是在第一次改变范围时,除了指令文本框以外的任何文本框的改变。$ watch触发器,稍后它不会。这里是我的代码Angularjs指令

$('.addNew').click(function(){ 
    var uniqid = Date.now(); 
    var html= ''; 
    html += '<section class="newItem" id="'+uniqid+'">'; 
    html += '<h4 style="margin: 10px 22px 8px 22px;color:#FF9900;border-bottom:1px dotted black;padding:1%;" > Grocery: <em>{{gName}}</em></h4>'; 
    html += '<div class="grosinput" style="width:0%;"><a href="#" class="stylish" data-uniqid="'+uniqid+'">-</a></div>'; 
    html += '<div class="grosinput" style="width:50%;">'; 
    html += '<lable style="color:#6699CC;font-size: 15px;">Name:</lable><input type="text" placeholder="Enter grocery item" name="name" ng-model="gName"/>'; 
    html += '</div>'; 
    html += '<div class="grosinput">'; 
    html += '<lable style="color:#6699CC;font-size: 15px;">Cost:</lable><input type="text" placeholder="Enter Cost" value="30" name="cost" cost-check ng-model="cost"/></div></section>'; 
    var $injector = angular.injector(['ng', 'grocery']); 
    $injector.invoke(function($rootScope, $compile) {alert('t'); 
     $('.grocadd').hide().after($compile(html)($rootScope)).fadeIn(1500); 
    }); 
}); 

这里是指令

app.directive('costCheck',function($compile,$rootScope){ 
$rootScope.gName= "What did i buy?"; 
    return{ 
     restrict: 'A', 
     link: function(scope,element,attrs){ 


       scope.$watch('cost',function(oldval,newval){alert(attrs.name); 
        if(attrs.name === 'cost'){ 
         alert(oldval+'--'+newval); 
        } 
       }); 

     } 

    } 
}); 

为什么会引发其他文本框也

+0

没有人看到这段代码吗? – user3498603

回答

0

请注意角依赖于脏检查,这意味着它会触发所有的手表到检查是否有脏东西来更新视图。

要么你应该把一个if条件检查newValoldVal不同,以作为未来:

scope.$watch('cost',function(newVal, oldVal){ 
    if (newVal !== oldVal){ 
    alert(oldval+'--'+newval); 
    } 
}); 

或者您可以使用attrs.$observe观察的属性:

我改变了指令从cost-check DOM来cost-check="{{cost}}"并用替换$watch$observe为:

attrs.$observe('costCheck', function(val) { 
    console.log(scope.$eval(val)); 
}); 

演示:http://jsfiddle.net/HB7LU/3018/