2014-03-13 26 views
16

我想在控制器中使用$compile而不是指令。可能嗎?我正在嘗試下面的代碼。

$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope) 

但這是引發範圍是未定義的錯誤。我試圖通過$scope函數內,但它不工作。

+0

http://stackoverflow.com/questions/12546945/difference-between-the-controller-link-and-compile-functions-when-definin – BKM

+0

http://stackoverflow.com/questions/15676614/directive-link -vs-compile-vs-controller – BKM

+1

你能解釋一下爲什麼你想在控制器中而不是在指令中編譯?控制器不應該知道DOM。 –

回答

17

Angular將如何知道您更改了DOM?您需要在添加html之前編譯您的html(使用$ compile服務)。

如果您絕對需要訪問指令外,您可以創建一個注入器。

$(function() { 
    // myApp for test directive to work, ng for $compile 
    var $injector = angular.injector(['ng', 'myApp']); 
    $injector.invoke(function($rootScope, $compile) { 
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope)); 
    }); 
}); 
10

這是值得大家注意的,在前面的答案(var $injector = angular.injector(['ng', 'myApp']);)噴油器不會追加編譯指令,當前運行的應用程序的角度,它會創建新的來代替。

爲新的指示動態添加到您的應用程序,你應該使用已經存在的噴油器:

$(function() { 
    angular.element(document).injector().invoke(function($rootScope, $compile) { 
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope)); 
    }); 
}); 

見最後一段中documentation

+0

好的答案謝謝。您只需忘記在函數內部注入$ rootScope;) – toregua

1

我這樣做

var SCOPE; 
app_module.controller('appController', function ($scope, $compile) { 
    SCOPE = $scope; 
    $scope.compile = function (elem_from, elem_to) { 
     var content = $compile(angular.element(elem_from))($scope); 
     angular.element(elem_to).append(content); 
    } 
}); 

使用這樣

SCOPE.compile(elem1.content, elem2); 
+0

元素1和2是什麼? –

+1

Elem1是源元素,您可以在其中找到要編譯的html結構。 Elem2是您將放置新編譯的html的地方。 – Inuart

5

我試圖@Vaibhav耆那教的答案,但沒有成功。多一點挖之後,這是我發現的角1.3工作,和jQuery:

$(function() { 
    angular.element(document).injector().invoke(['$compile', function ($compile) { 
    // Create a scope. 
    var $scope = angular.element(document.body).scope(); 
    // Specify what it is we'll be compiling. 
    var to_compile = '<div ng-attr-tooltip="test">Cancel</div>'; 
    // Compile the tag, retrieving the compiled output. 
    var $compiled = $compile(to_compile)($scope); 
    // Ensure the scope and been signalled to digest our data. 
    $scope.$digest(); 
    // Append the compiled output to the page. 
    $compiled.appendTo(document.body); 
    }); 
}); 
1

我的,當我需要重新編譯我的HTML應用頁面上的變化通過以下方式重新編譯我的HTML 。

它發生在我試圖去其他鏈接並返回到頁面,但由於某些原因角碼不編譯。

所以我通過在加載事件中再次編譯頁面的html部分來解決這個問題。

function OnLoad() { 
angular.element("form:first").injector().invoke(['$compile', function ($compile) { 
    var $scope = angular.element("form:first").scope(); 
    $compile("form:first")($scope); 
}]); 
} 

下面是應用聲明。

<form ng-app="formioApp" ng-controller="formioAppCtrl"> 

和OnLoad()函數在該頁面上的html元素的onload事件中分配。

相關問題