2016-01-20 81 views
5

我是AngularJS的新手,目前正在努力解決以下問題。ng-change對輸入不起作用

正如你所看到的here in my plnkr我可以改變$scope.myDate.value的值。

現在的問題是,在<input>中添加ng-change="barFunc()"時,我無法在此功能中使用該範圍。

如何在ng-changeng-watch這裏工作? 如果有人能讓我的plnkr工作,那將會很棒。

<!DOCTYPE html> 
 
<html ng-app="demo"> 
 
<head> 
 
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> 
 
    <link href="//rawgithub.com/g00fy-/angular-datepicker/1.0.3/dist/index.css" rel="stylesheet"> 
 
    <style> 
 
     input {margin: 45px 0 15px 0;} 
 
     pre{padding: 15px; text-align: left;} 
 
    </style> 
 
</head> 
 
<body> 
 
<div class="container"> 
 
    <div class="row"> 
 
     <div class="col-md-4"> 
 
      <div ng-controller="foo"> 
 
       <input type="datetime" class="form-control" date-time ng-model="myDate.value" 
 
        ng-change="barFunc()" format="yyyy-MM-dd hh:mm:ss" placeholder="Select datetime"> 
 
       <pre>myDate: {{myDate.value}}</pre> 
 
       <pre>myDate + " abc": {{ custom.value }}</pre> 
 
      </div> 
 
     </div> 
 
    </div> 
 
</div> 
 

 
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<script src="//code.angularjs.org/1.4.8/angular.js"></script> 
 
<script src="//rawgithub.com/g00fy-/angular-datepicker/1.0.3/dist/index.js"></script> 
 
<script> 
 
angular.module('demo', ['datePicker']).controller('foo',['$scope', function($scope){ 
 
    $scope.myDate = { 
 
     value: '' 
 
     }; 
 
     
 
    $scope.barFunc = function() { 
 
     $scope.custom.value = $scope.myDate.value + " abc"; 
 
    }; 
 
}]); 
 
</script> 
 
</body> 
 
</html>

回答

2

你之前定義$scope.custom您可以 訪問$scope.custom.value

+0

是的!參見工作[plnkr](http://plnkr.co/edit/hKohYQSC5SG7ZF33qz45?p=preview)。 – herrh

2

我會用$在這種情況下手錶:

在你的控制器

$scope.custom = { 
    value : '' 
}; 

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

$scope.barFunc = function() { 
    $scope.custom.value = $scope.myDate.value + " abc"; 
}; 

plunkr

+0

感謝這個ng-watch的例子;) – herrh

2

你可以建立這樣的守望者:

$scope.$watch('myDate', function(oldValue, newValue) { 
$scope.barFunc(newValue); 

});

,但你還需要定義自定義對象:

$scope.custom = { 
    value: '' 
    }; 

,它應該工作。我不覺得這是最好的解決方案 - 我通常覺得如果我設置了觀察者,因爲我不明白爲什麼某些事情沒有按預期工作,最好找出爲什麼它不起作用。我明白這就是你想要做的,並且只是提供這種能夠快速解決你的問題的東西,如果這是你需要的。

+0

如果我在上面的回答中沒有清楚說明 - 我不知道爲什麼ng-change在這裏不起作用,即使在你定義了你的自定義對象之後,也沒有時間去弄清楚。對於是否有其他人提供該問題的解決方案,我們會非常感興趣。 –