gpt4 book ai didi

javascript - Angular 在自定义指令中设置新变量

转载 作者:行者123 更新时间:2023-12-03 07:14:10 25 4
gpt4 key购买 nike

我正在学习 Angular 类(class),作为一个完全的新手,我有一个关于自定义指令的新手问题要问。我想知道我们如何在该自定义指令中设置新变量并在我们的 View 中访问它们,如果有人可以清楚地解释这一点,这是否可能?

例如:

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {

$scope.person = {
name: 'John Doe',
address: '555 Main St., New York, NY 11111'
}

}]);

myApp.directive("searchResult", function() {
return {
restrict: 'AECM',
templateUrl: 'directives/searchresult.html',
replace: true,
scope: {
personName: "@",
personAddress: "@",
newVariable: "someValue"
}
}
});

搜索结果.html

<a href="#" class="list-group-item">
<h4 class="list-group-item-heading">{{ personName }}</h4>
<p class="list-group-item-text">
{{ personAddress }}
</p>
<p class="list-group-item-text">
{{ newVariable }}
</p>

main.html

<label>Search</label>
<input type="text" value="Doe" />
<h3>Search Results</h3>
<div class="list-group">
<search-result person-name="{{ person.name }}" person-address="{{ person.address }}" newVariable="{}"></search-result>

最佳答案

对本地范围使用链接函数

myApp.directive("searchResult", function() {
return {
restrict: 'AECM',
templateUrl: 'directives/searchresult.html',
replace: true,
scope: {
personName: "@",
personAddress: "@"
},
link: function(scope, elem, attr) { scope.newVariable='something'; },
};
});

关于javascript - Angular 在自定义指令中设置新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36495212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com