使用另一个控制器的AngularJS指令

AngularJS directive using another controller

本文关键字:AngularJS 指令 控制器 另一个      更新时间:2023-09-26

我正在尝试创建一个指令,将输出一个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>