gpt4 book ai didi

javascript - 访问 angularjs 中自定义指令内 Controller 中定义的函数

转载 作者:行者123 更新时间:2023-11-28 05:51:21 25 4
gpt4 key购买 nike

我是 AngularJS 的新手。在定义方法和属性时,我遵循 Controller 作为语法。我刚刚创建了一个自定义指令来显示人员的搜索结果。我在 Controller 内定义了一个方法,用于我的自定义指令搜索结果。如何使用 Controller 作为语法访问自定义指令中的 formattedAddress 函数。

app.js

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider) {

$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController',
controllerAs: 'main'
})

.when('/second', {
templateUrl: 'pages/second.html',
controller: 'secondController',
controllerAs: 'second'
})

.when('/second/:num', {
templateUrl: 'pages/second.html',
controller: 'secondController',
controllerAs: 'second'
})

});

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

var self = this;

self.people = [{
name: 'John Doe',
address: '555 Main St.',
city: 'New York',
state: 'NY',
zip: '11111'
}, {
name: 'Jane Doe',
address: '333 Second St.',
city: 'Buffalo',
state: 'NY',
zip: '22222'
}, {
name: 'George Doe',
address: '111 Third St.',
city: 'Miami',
state: 'FL',
zip: '33333'
}];

self.formattedAddress = function(person) {

return person.address + ', ' + person.city + ', ' + person.state + ' ' + person.zip;

};

}
]);

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



}
]);

myApp.directive("searchResult", function() {
return {
restrict: 'EA',
templateUrl: 'directives/searchresult.html',
replace: true,
scope: {
personObject: "=",
formattedAddressFunction: "&"
}
}
});

我无法访问 formattedAddress 内的 person 对象。

ma​​in.html

<label>Search</label>
<input type="text" value="Doe" />

<h3>Search Results</h3>
<div class="list-group">
<search-result person-object="main.person" formatted-address-function="main.formattedAddress(aperson)" ng-repeat="person in main.people"></search-result>
</div>

searchresult.html

<a href="#" class="list-group-item">
<h4 class="list-group-item-heading">{{ personObject.name }}</h4>
<p class="list-group-item-text">
{{ formattedAddressFunction({ aperson: personObject }) }}
</p>
</a>

最佳答案

您应该为此使用 Angular 过滤器。用于限制单词字母的示例过滤器。

angular.module('app').filter('limitLetters', function() {
/**
* Limits the letters of the input string
* @param value {string} the string to be limited
* @param max {number} the max number of letters allowed
*/
return function(value, max) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
return value + ' …';
};
});

关于javascript - 访问 angularjs 中自定义指令内 Controller 中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38046349/

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