指令参数嵌套控制器简单示例

Directive Parameters Nested Controller Simple Example

本文关键字:简单 控制器 参数 嵌套 指令      更新时间:2023-09-26

这是代码

app.directive('hello', function() {
    return {
        restrict: "E",
        templateUrl: "/Angular/Modules/Selector.html",
        controller: function () {
          this.message = [want the attribute message here]
        }
    };
});

和标记

<hello message="hello world instance 1"></hello>
<hello message="hello world instance 2"></hello>

最后,问题

如何将每个hello元素的属性获取到控制器实例中?

绑定数据源属性

<hello ... datasource="/jsonData.json"></hello>
<hello ... datasource="/otherJsonData.json"></hello>

更多控制器代码

$http.get($attrs.datasource).success(function (data) { ... });'

数据源是共享的,但我需要两个单独的实例。

感谢Blackhole的建议!

工作代码

正如他所解释的那样,我现在可以得到这些属性了。我确实注意到属性奇怪地变为小写,但这对我来说很好。此外,Scope:{}还可以创建孤立实例。

app.directive('selector', function () {
    return {
        restrict: "E",
        templateUrl: "/Angular/Modules/Selector.html",
        scope : {},
        controller:  function ($http, $scope, $element, $attrs) {
           ...
            this.displayField = $attrs.displayfield;
           ...
            $http.get($attrs.datasource).success(function (data) {
            ...
            });
        },
        controllerAs : "selector"
    };
});

标记

除了我添加的新属性而不是消息之外,没有什么变化。

<selector id="selector1" datasource="/Company/CompanyListViewData2"
    displayfield="Name"></selector>
<selector id="selector2" datasource="/Employee/SimpleEmployeeListViewData"
    displayfield="LastNameFirstName"></selector>

再次感谢,这太棒了!