我正在学习有关Angular的课程,作为一个完整的新手,我有一个关于自定义指令的新手问题。我不知道我们如何在该自定义指令中设置新变量并在我们的视图中访问它们,即使有人可以清楚地说明这一点,这是否有可能?
例如:
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"
}
}
});
searchresult.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>
最佳答案
将link function
用于本地scope
myApp.directive("searchResult", function() {
return {
restrict: 'AECM',
templateUrl: 'directives/searchresult.html',
replace: true,
scope: {
personName: "@",
personAddress: "@"
},
link: function(scope, elem, attr) { scope.newVariable='something'; },
};
});