我有一个简单的指令,我想访问模板中链接函数中的变量。 我怎样才能做到这一点?
我的指令 :
app.directive("hello", function() {
return {
restrict: "E",
template: '<div> '+str+' <div/>'
link : function(scope, element, attrs) {
var str = "hello";
}
}
});
这是代码笔上的代码:演示
变量添加到作用域中,它们将在模板中可用
scope.str = "hello";
并且您的模板应使用角度表达式
template: '<div>{{str}}<div/>',
所以你的指令会像
app.directive("hello", function() {
return {
restrict: "E",
template: '<div>{{str}}<div/>',
link : function(scope, element, attrs) {
scope.str = "hello";
}
}
});
编辑
如果要绑定 html,请使用 ngbindHtml
请找到波兰兹罗提
我需要在这里解释您有多种方法,所以请考虑双方的变化需要我的意思是您想从指令调用发送变量
<html ng-app="app">
<body>
<hello data-str="'I am don'"></hello>
</body>
</html>
这里 data-str 意味着有 str 是变量,它有文本"我是唐",就是这样
现在
angular.module("app", []);
angular.module("app").directive("hello", function() {
return {
scope:{
str:"="
},
restrict: "E",
template: '<div>{{linkVar}}{{str}}<div/>',
link : function(scope, element, attrs) {
scope.linkVar = 'It works!'
console.log(scope.str);
}
}
});
这里
你可以在我添加的指令对象中看到这一点
scope:{
str:"="
},
在这里,我们决定当指令像这样调用 html 时将提供"str",而不仅仅是这样 请注意
现在
scope.linkVar = 'It works!'
这是你应该看到的最重要的事情 scope.linkVar 意味着你只有名称为 str = "hello" 的 JavaScript 变量; 这不是角度的方式,因此角度不会更新其所有引用。我的意思是当您在模板中使用时。
现在希望清楚,如果是,请告诉我。玩得开心
卡贾明
你可以使用'this'
app.directive("hello", function() {
return {
this.str = '';
restrict: "E",
template: '<div> '+this.str+' <div/>'
link : function(scope, element, attrs) {
this.str = "hello";
}
}
});