2013-06-23 31 views
0

我希望有一個相當簡單的解決方案。編譯角度直到模型更改不起作用

我有一個從文件加載HTML的指令設置。然後它應該使用Angular編譯該HTML。該指令:

angular.module('wc.directives', [], function($compileProvider) { 
    $compileProvider.directive('view', function($compile) { 
    return function(scope, element, attrs) { 
     scope.$watch(
     function(scope) { 
      // watch the 'view' expression for changes 
      return scope.$eval(attrs.view); 
     }, 
     function(value) { 
      // when the 'view' expression changes 
      $.ajax({ 
      url: '/partials/' + value, 
      success: function(data) { 
       element.html(data); 
       $compile(element.contents())(scope); 
      } 
      }); 
     } 
    ); 
    }; 
    }); 
}); 

的,這是應該負荷(玉)一個東西的一個例子

input#nameInput.nameField(ng-model='name', type='text') 
h1 {{ name }} 

頁面加載後,{{名}}可見。但是,當您開始在文本字段中輸入內容時,{{name}}會更新您輸入的任何內容。

如果element.html$compile語句不在ajax success回調中,則所有內容按預期進行編譯。

回答

0

這是一個簡單的解決方案,正如所料。

我只需要在$compile聲明後面加上scope.$apply();即可。

編輯:更好的解決方案是使用$http。這裏是最後的工作代碼:

angular.module('wc.directives', [], function($compileProvider) { 
    $compileProvider.directive('view', function($compile, $http) { 
    return function(scope, element, attrs) { 
     scope.$watch(
     function(scope) { 
      // watch the 'view' expression for changes 
      return scope.$eval(attrs.view); 
     }, 
     function(value) { 
      // when the 'view' expression changes 
      if (value !== null) { 
      $http.get('/partials/' + value).success(function(data) { 
       element.html(data); 
       $compile(element.contents())(scope); 
      }); 
      } 
     } 
    ); 
    }; 
    }); 
}); 
2

你是讓你的生活更難使用jQuery的ajax。選擇AngularJS $http,你不需要撥打$apply(因爲$http會爲你做!)。

總之 - 除非你有非常特別的理由使用jQuery的ajax刪除它並使用$http而不是

+0

$ http是我嘗試的第一件事,但我不知道如何正確注入它。我回去弄清楚如何正確注入它,它很好地工作,謝謝! –