我正在尝试创建一个指令,该指令将输出一个使用来自 Controller 的数据的 HTML 模板。
在 sample.js 中我添加了一个模块、 Controller 和指令
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>
由于 Controller 是在主体中创建的,所以我希望子元素能够使用它的属性/方法。但是没有数据显示(没有 ng-show,数据显示正常)。
在这个简化的示例中,我可以将 ng-show 移动到 HTML 中的 DOM 元素,但在我的实际应用程序中,这不是一个选项。我真的需要我的指令才能使用我的 Controller 中的属性(和方法)。
这可能吗?为了让它发挥作用,我错过了什么?
最佳答案
由于您使用的是隔离范围,因此您必须声明一些属性才能像这样使用它
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>
关于javascript - 使用另一个 Controller 的 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802668/