2016-01-03 22 views
1

我嘗試使用下面的代碼

(function(angular) { 
    var app = angular.module("directiveModule1",[]); 
    app.controller('testController', ['$scope', function($scope){ 
    $scope.UserName = "afh"; 
    }]); 
    app.directive("linkFuncDirective",['$compile', function($compile) { 
return { 
    link: function(scope, element, attrs,controller) { 
    var markUp = "<input type = 'text' ng-model ='UserName'/>{{UserName}}</br>"; 
    var linkFunc = $compile(markUp); 
    var content = linkFunc(scope); 
    angular.element(element).html(content); 
    //angular.element(element).html($compile(markUp)(scope)); 
    } 
}; 
}]); 
})(window.angular); 

進行編譯範圍靜態DOM和我的HTML低於

<html> 

<head> 

    <script data-require="[email protected]*" data-semver="1.4.0-beta.5"  src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script> 
    <script src="directiveWithLinkFunction.js"></script> 

</head> 

<body ng-App="directiveModule1"> 

    <div ng-controller="testController"> 
    <div link-func-directive></div> 
    </div> 

</body> 

</html> 

和我得到以下o/p

[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]] 

試圖瞭解代碼中寫錯了什麼,高度讚賞任何幫助

回答

1

HTML背後的原因是有上視圖[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]]時,必須使用$compile服務,以下爲返回編譯DOM

編譯的HTML的一行
<input type="text" ng-model="UserName"> 
<span class="ng-binding ng-scope"></span> 
<br class="ng-scope"> 

所以基本上它有3個元素,第1個是輸入元素,第2個是跨度&第3個是br中斷標記。因此,當您嘗試使用.html方法將其作爲HTML添加到頁面時,jQLite將在內部採用該對象並應用.toString()方法來確保它應接受該字符串。這就是你在輸出中獲得[Object...]的原因。


基本上你的問題是你要分配編譯角度DOM html內容的指令元素的HTML,這是沒有意義的。

它應該是.append函數而不是.html作爲角度編譯的DOM將被注入將啓用綁定。

element.append(content); //would append the DOM with angular compiled DOM. 
+0

欣賞詳細的解釋。謝謝 –

+0

很高興聽到這個消息。謝謝:) –

-1

你的代碼有點亂。先嚐試清理。

  1. 給予限制屬性的指令
  2. ,如果你沒有一個必填字段,那麼你並不需要一個controller參數
  3. 你爲什麼不只是簡單的使用模板爲您的指令
+2

我知道我幾乎可以使用模板。就這樣你理解,我不是簡單地試圖使這個指令工作,而是試圖詳細地試驗和學習編譯。 –

0

爲什麼你想先編譯一下?你可以使用一個簡單的模板。

+0

是的,這也是我的觀點:) – Iamisti