2016-04-24 50 views
0

我正在處理具有相同指令的應用程序,但內容更改和模板取決於模塊中控制器的ID。如何在Angularjs中創建自定義指令,以改變其在應用程序中使用ID的狀態?

app.directive('glTranslate', function() { 
     return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      var key = element.text(); 
     attrs.$observe('options', function(value) { 
     var options; 

     try { 
      options= JSON.parse(value); 
      element.text(I18n.t(key, options)); 
     } catch (err) { 
      // SyntaxError maybe thrown as the options string is dynamically updated through Angular bindings 
      // and the options string may be momentarily be syntactically incorrect 
      console.log("Error parsing options: " + value + "\nError:"+ err.message + "\n"); 
     } 
     }); 
    } 
    }; 
}); 
+0

份額一些代碼,所以我會建議做 –

+0

這將有助於你幫我出的文檔。我們可以使用Id:鏈接後: –

+1

官方文檔在https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object沒有可以設置的「Id」屬性 - 它真的沒有意義。您能否添加一些關於您如何看待此功能的示例,例如給定一個ID,輸出應該是什麼樣子。我懷疑你需要在指令html中定製一些東西,或者創建不同的指令,而不是混淆指令_itself_。 – Rhumborl

回答

1

如果我正確理解你,要根據某些條件動態設置指令的模板,可以在指令中使用ng-include。下面的僞代碼工作。它包含一個示例指令,該指令具有傳遞給它的動態模板選擇屬性和簡單的HTML使用。不用說,儘管模板內容各不相同,但在這裏它們使用相同的指令控制器及其附帶的功能。希望這可以幫助。

.directive("dynaDirective", function() { 
 
    return { 
 
    template: '<ng-include src="getTemplateUrl()"/>', 
 
    scope: { 
 
     someData: '=' 
 
    }, 
 
    restrict: 'E', 
 
    controller: function($scope) { 
 
     //function used on the ng-include to resolve the template 
 
     $scope.getTemplateUrl = function() { 
 
     //basic handling 
 

 
     return "templateName" + $scope.someData.type; 
 

 
     } 
 

 
     $scope.doSomething1 = { 
 
     //...... 
 
     } 
 
     
 
     $scope.doSomething2 = { 
 
     //...... 
 
     }  
 
    } 
 
    }; 
 
});
<dyna-directive some-data="someObject"></dyna-directive>

+0

感謝您的答案 –

相關問題