简体   繁体   English

自定义元素指令和属性

[英]Custom Element Directives and attributes

myPage.html myPage.html

<div ng-controller="MyPageCtrl">
    <my-custom-directive arg1="{{currentObj.name}}"></my-custom-directive>
<div>

in myPageCtrl.js (Controller) myPageCtrl.js中(控制器)

app.controller("MyPageCtrl", ["$scope", function ($scope) {
          $scope.currentObj = {"name":"Collin"};
    }]);

And this is how my directive code looks like 这就是我的指令代码的样子

app.directive("myCustomDirective", [function () {
    return {
        restrict: "E",
        controller: "MyCustomDirCtrl"
    };
}]);

Finally here's my directive's controller, 最后是我指令的控制器

app.controller("MyCustomDirCtrl", ["$attrs", function ($attrs) {
      var arg = $attrs.arg1;
      alert('Arg '+arg);
}]);

The alert just displays "{{currentObj.name}}" and not the value of the name property of currentObj. 警报仅显示“ {{currentObj.name}}”,而不显示currentObj的name属性值。

Please can you suggest me ways to figure this out. 请您为我提出解决方案的建议。

Thanks. 谢谢。

Not sure why did you use $attrs for a controller. 不知道为什么将$ attrs用作控制器。 Just use a normal $scope. 只需使用普通的$ scope。

myPage.html myPage.html

<div ng-controller="MyPageCtrl">
    <my-custom-directive arg1="{{currentObj.name}}"></my-custom-directive>
<div>

myPageCtrl.js (Controller) myPageCtrl.js(控制器)

app.controller("MyPageCtrl", ["$scope", function ($scope) {
          $scope.currentObj = {"name":"Collin"};
    }]);

myCustomDirective myCustomDirective

app.directive("myCustomDirective", [function () {
    return {
        restrict: "E",
        controller: "MyCustomDirCtrl"
    };
}]);

Directive's controller (change $attrs to $scope here), 指令的控制器 (此处将$ attrs更改为$ scope),

app.controller("MyCustomDirCtrl", ["$scope", function ($scope) {
      var arg = $scope.arg1;
      alert('Arg '+arg);
}]);

Instead of accessing the attr from your controller, you could access it from your directive using the link function. 除了可以从控制器访问attr之外,还可以使用链接功能从指令中访问它。

app.directive("myCustomDirective", [function () {
    return {
        restrict: "E",
        controller: "MyCustomDirCtrl",
        link: function(scope, element, attr) {
            alert(attr.arg1);
        }
    };
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM