更改2个指令的监听器应该对另一个指令产生一个动作

时间:2015-06-24 15:07:01

标签: angularjs

我已经解决了这个问题太久了,需要一些帮助。

我制作了一个片段,因此问题更容易理解 目的:使DURATION输入readOnly,当FROM AND TO为!= null

问题仍然存在于指令如何一起沟通。

我认为代码比文字说明更好......



(function(){

 
  angular.module('app', [])
  
  .controller('AppController', function($scope){
  
    $scope.from = 3600;
    $scope.to = 7200;
    $scope.duration = "null";
  
  })
  
  
  .directive('hourInput', function(){
    
    return {
      restrict : 'A',
      require : 'ngModel',
      link : function(scope, element, attrs, modelCtrl){
        
        //Change scope copy of view
        modelCtrl.$formatters.push(function(seconds){
          if(seconds == "null" || seconds == null){
				return "";
		  }		
		 var sec_num = parseInt(seconds, 10); 
		 var hours   = Math.floor(sec_num / 3600);
		 var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
		 hours = (hours < 10) ? "0" + hours : hours;
		 minutes = (minutes < 10) ? "0" + minutes : minutes;
		 //Only hours matters
		 return hours + ":" + minutes;
        });
        
        //Change scope copy of model
        modelCtrl.$parsers.push(function(time) { 
			if(time.length != 5){						
				return "null";
			} 
			var hours = parseInt(time.substring(0, 2));
			var minutes = parseInt(time.substring(3));
			return ((hours * 60) + minutes) * 60 + "";
		}); 
        
        
        //The problem is here
        /*
         Goal : set duration on readOnly when from || to == "null"
         
         Problem : 
         This can't happen here, because can't watch both inputs.
         
         Solution: 
         - Create 2 directives? (1 in each input : from and to)
         - COntroller?
         - ...
        
        NOte : I know I can watch on changes with :
        modelCtrl.$viewChanheListener... but the problem is: 
        if FROM == null -> duration will ne readOnly even if TO != null
        
        */
        
      }
    
    
    };
    
  });
  
 })();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>


<div ng-app="app" ng-controller="AppController">
  
  <input type="text" ng-model="from" placeholder="from" hour-input/> <br />
  <input type="text" ng-model="to" placeholder="to" hour-input/> <br />

  <input type="text" ng-model="duration"  placeholder="duration" get-duration/> <br />
  
{{from}}
</div>
&#13;
&#13;
&#13;

0 个答案:

没有答案