简体   繁体   English

如何在指令中访问属性的值?

[英]How do I access an attribute's value in a directive?

I am trying to bind a model to an attribute in a directive. 我试图将模型绑定到指令中的属性。

Javascript -- Javascript-

function Main($scope) {
    $scope.text = "abc"
};

angular.module("myApp", [])
.directive("load", function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, attrs) {
           console.log(attrs);
           element.html(someFunction(attrs.text));
        }
    };
});

HTML -- HTML-

<div ng-controller="Main">
    <load text="Hello {{text}}"></load>
</div>

You can find the jsFiddle here . 您可以在此处找到jsFiddle。 In the fiddle I have done away with someFunction . 在小提琴中,我取消了someFunction

Here is a quick plunk showing 5 different ways to get to scope from within a directive. 这是一个简短的示例,展示了从指令中获取作用域的5种不同方法。 The last one is the one you want: http://plnkr.co/edit/e2mMAq 最后一个是您想要的一个: http : //plnkr.co/edit/e2mMAq

Based on what I believe you are trying to do, you need to make two modifications: 根据我认为您要尝试执行的操作,您需要进行两项修改:

  1. You have replace set to true, so you should probably add a template to your code to replace the element with your new markup. 您将replace设置为true,因此您可能应该在代码中添加模板,以用新的标记替换元素。

  2. At the time that the linking phase occurs, the interpolation has not been evaluated yet, so you need to observe the attribute in order to look for changes. 在链接阶段发生时,尚未评估插值,因此您需要观察属性以查找更改。

      angular.module('myApp', []) .directive('load', function($compile) { return { restrict: 'E', replace: true, link: function (scope, element, attrs) { console.log(attrs); element.html(attrs.text); attrs.$observe('text', function(value) { console.log('new value = ' + value); element.html(value); }); } }; }); 

Take a look at the section observing interpolated attributes for more details. 请查看观察插值属性的部分以获取更多详细信息。

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

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