[英]AngularJS directive using another controller
我正在嘗試創建一個指令,該指令將輸出使用來自控制器的數據的HTML模板。
在sample.js中,我添加了一個模塊,控制器和指令
var app = angular.module("myApp", []);
app.controller("MyCtrl", function($scope) {
$scope.someProperty = true;
})
app.directive("myElement", function() {
return {
restrict: "E",
scope: {name: "@"},
template:
'<div ng-show="someProperty">' +
' <p>This element is called {{name}}</p>' +
'</div>',
replace : true,
transclude : false
}
})
我正在將元素與以下HTML一起使用
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="sample.js"></script>
</head>
<body ng-controller="MyCtrl">
<div><my-element name="Mark"></my-element></div>
<div><my-element name="Vink"></my-element></div>
</body>
</html>
由於控制器是在主體中創建的,因此我希望子元素能夠使用它的屬性/方法。 但是沒有數據顯示(沒有ng-show,數據顯示正常)。
在這個簡化的示例中,我可以將ng-show移到HTML中的DOM元素,但是在我的實際應用程序中,這不是一個選擇。 我真的需要我的指令才能使用控制器中的屬性(和方法)。
這可能嗎? 我想念什么才能使它正常工作?
由於您使用的是隔離范圍,因此必須聲明someProperty才能使用它
app.directive("myElement", function() {
return {
restrict: "E",
scope: {
name: "@",
someProperty: "="
},
template:
'<div ng-show="someProperty">' +
' <p>This element is called {{name}}</p>' +
'</div>',
replace : true,
transclude : false
}
});
你可以這樣使用
<my-element name="Vink" some-property="someProperty"></my-element>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.