$ watch指令不起作用

时间:2014-02-16 06:56:11

标签: angularjs angularjs-directive

我的$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;
        };

      }
    };
  }]);
})();

1 个答案:

答案 0 :(得分:0)

尝试将var updateHTML更改为function 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'
},
...