2014-02-16 102 views
0

任何原因我的$scope.$watch不起作用?當我輸入時,我在控制檯中看不到更新。

(function() { 
    'use strict'; 

    wikiApp.directive('wikiMarkdownEdit', ['pathSvc', function (pathSvc) { 
    var getFullPath = pathSvc.getFullPath; 
    return { 
     restrict: 'E', 
     templateUrl: getFullPath('html/directives/markdownEdit.html'), 
     replace: true, 
     scope: { 
     model: '=', 
     formId: '@', 
     rows: '@', 
     placeholder: '@' 
     }, 
     controller: function($scope, $sce, $attrs, $log) { 
     var converter = new Showdown.converter(); 

     $scope.showPreview = false; 

     /** 
     * Keep the preview up to date 
     */ 
     $scope.$watch('model', updateHTML); 
     var updateHTML = function() { 
      var html = converter.makeHtml($scope.model || ''); 
      console.log(html); 
      // jQuery('#' + $scope.formId + 'Preview').html('1111'); 
     }; 
     updateHTML(); 

     /** 
     * Sync the height of the preview div with the textarea 
     **/ 
     var lastHeight = 0; 
     var getHeight = function() { 
      var newHeight = jQuery('#' + $scope.formId).outerHeight(); 
      if (lastHeight === newHeight || newHeight < 20) { 
      setTimeout(getHeight, 100); 
      return; 
      } 
      lastHeight = newHeight; 
      jQuery('#' + $scope.formId + 'Preview').height(newHeight); 
      setTimeout(getHeight, 100); 
     }; 
     getHeight(); 

     /** 
     * Toggle preview button callback 
     */ 
     $scope.togglePreview = function() { 
      $scope.showPreview = !$scope.showPreview; 
     }; 

     } 
    }; 
    }]); 
})(); 
+0

你能證明你的HTML?這可能是因爲您沒有正確綁定模型,並且在鍵入內容時未更新該屬性。 –

回答

0

嘗試改變var updateHTMLfunction updateHTML,則不能使用的定義之前,var定義的函數。

另一種方式推薦:

function updateHTML() { 
    var html = converter.makeHtml($scope.model || ''); 
    console.log(html); 
}; 

$scope.$watch(function() { 
    return $scope.model; 
}, updateHTML); 

還有一兩件事,在你的指導範圍內,你的意思是model有界到ngModel?如果是的話,試試這個方法:

... 
scope: { 
    ngModel: '=' 
}, 
... 

或者

... 
scope: { 
    model: '=ngModel' 
}, 
...