【发布时间】:2014-01-14 14:52:24
【问题描述】:
ReferenceError: 数据未定义
Angularjs 将变量传递给控制器中的过滤器
大家好
我还是 Angularjs 的新手,所以可能完全错了。
我正在尝试显示 twitter 提要并使用过滤器,该过滤器将使用工厂来解析 twitter 提要中的链接。
我收到一个错误 ReferenceError: data is not defined
我是否需要将数据从“TwitterCtrl”传递到“parseTwitterLinks”
我该怎么做?
html 是这样的
<p><span id="retweet-icon"></span><span ng-bind-html-unsafe="tweet.text | parseTwitterLinks"></span></p>
TwitterCtrl
myApp.controller('TwitterCtrl', ['$scope','$http','twitter','$rootScope','$filter','parseTwitterLinksFilter', function($scope, $http, twitter, $rootScope, $filter, parseTwitterLinksFilter){
$scope.tabId = false;
$scope.tweet = false;
$scope.$on('tabId', function(event, tabId) {
if(tabId != $scope.tabId) {
$scope.tabId = tabId;
if($scope.tabId) {
$scope.fetchTweet();
} else {
$scope.tweet = {};
}
}
});
$scope.fetchTweet = function() {
var dataUrl = '/twitter?tab=' + $scope.tabId;
$http({
method: 'GET',
url: dataUrl
}).success(function(data, status, headers, config){
if(data) {
$scope.tweet = data;
} else {
$scope.tweet = {};
}
}).error(function(data, status, headers, config){
$scope.tweet = {};
});
};
}])
过滤器
myApp.filter('parseTwitterLinks', [function(){
return function(text) {
var tweet = data;
if(typeof tweet.text != 'undefined') {
tweet.text = twitter.parseLinks(tweet.text);
}
$scope.tweet = tweet;
}
return tweet.text;
}]);
解析链接的工厂
myApp.factory('twitter', function($rootScope) {
return {
parseLinks: function(str) {
var that = this;
str = str || '';
str = that.parseUrl(str);
str = that.parseUsername(str);
str = that.parseHashtag(str);
return str
},
parseUrl: function(str) {
str = str || '';
return str.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=~]+/g, function(url) {
return '<a href="'+url+'" target="_blank">'+url+'</a>';
});
},
parseUsername: function(str) {
str = str || '';
return str.replace(/[@]+[A-Za-z0-9-_]+/g, function(username) {
return '<a href="http://twitter.com/'+username.replace("@","")+'" target="_blank">'+username+'</a>';
});
},
parseHashtag: function(str) {
str = str || '';
return str.replace(/[#]+[A-Za-z0-9-_]+/g, function(tag) {
return '<a href="http://twitter.com/search?q='+tag.replace("#","%23")+'" target="_blank">'+tag+'</a>';
});
}
}
});
【问题讨论】:
标签: angularjs filter angularjs-filter