I have two controllers on single page. For some reason only one of them works at a time. That is if I comment the lower div. Then upper one works and vice-versa.
index.html
<div ng-controller="MessageController as ctrl">
{{ctrl.messages}}
</div>
<div ng-controller="CommentController as ctrl">
{{ctrl.comments}}
</div>
app.js
var app = angular.module('plunker', []);
var prefix = 'http://jsonplaceholder.typicode.com';
app.controller('MessageController', ['$http', function ($http) {
$this = this;
$http.get(prefix + '/posts/1').success(function (response) {
$this.messages = response;
return response;
});
}]);
app.controller('CommentController', ['$http', '$scope', function ($http) {
$this = this;
$http.get(prefix + '/posts/2').success(function (response) {
$this.comments = response;
return response;
});
}]);
Here's plucker http://plnkr.co/edit/BXzj9GeP88BQeIA3UTWN?p=preview
You're issue is that $this is leaking onto the global scope. If you prefix the declaration with the var keyword it will reside on each controller constructors lexical scope.
app.controller('CommentController', ['$http', '$scope', function ($http) {
var $this = this;
$http.get(prefix + '/posts/2').success(function (response) {
$this.comments = response;
return response;
});
}]);
Related
I'm using angularjs with Django.
Here is my angularjs script:
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope, $http){
$scope.name = 'sh';
$http.get('http://127.0.0.1:8000/json/ls/').then(function(response){
$scope.code = response.status;
$scope.text = response.statusText;
$scope.data = response.data;
},function(){
$scope.message = 'not found!';
});
});
And here's my http://127.0.0.1:8000/json/ls/ page's result:
{'record':[{'name':'your name','post':'dp'},{'name':'sdfsdfyour name','post':'sdfsfsfdp'},{'name':'your namefdsfsd','post':'dpsfdfsdf'},{'name':'your namesdfsdfs','post':'dpfsfdsfs'}]}
But $http.get('http://127.0.0.1:8000/json/ls') function showing me it's $scope.message's data as result. And you know that this result will be only shown while $http.get() will be failed to find the specific page. Have any suggestion/solution, please?
Hi I want to call a function after clicking on a button which is added to dom after angular is loaded. I dont know if this is possible in the way I am trying it, but I do know that my current code doesn't call the alert function.
After sending a search request to my backend, I get a list data entrys, which I display as hrefs.
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
results in
John Doe
Complete Code:
var appModule = angular.module('graph', [])
appModule.controller('graphCtrl', ['$scope', '$http', '$compile', function ($scope, $http, $compile) {
$scope.search = function () {
var data = {
}
$http.get('/api/search/?q=' + $scope.searchfield, data).success(function (data, status, headers, config) {
var result = data;
var searchResultsContainer = document.getElementById("dropdownId");
while (searchResultsContainer.firstChild) {
searchResultsContainer.removeChild(searchResultsContainer.firstChild);
}
for (i in result) {
var my_form = document.createElement("a");
my_form.setAttribute("href", result[i].url)
my_form.setAttribute("ng-href",'#here')
my_form.setAttribute("ng-click", "alert(1)")
my_form.setAttribute("style", "display:block;")
my_text = document.createTextNode(result[i].caption)
my_form.appendChild(my_text)
searchResultsContainer.appendChild(my_form)
}
})
}
$scope.alert = function(){
alert("Hello! I am an alert box!!");
}
}
I am working on a social feed that displays charitable activities. It's supposed to look like the second activity in this image:
But as you can see, every time that angular-infinite-scroll goes to fetch the next batch of activities, it adds a broken template to the top of the feed.
This is the function that's called to get more activities:
feedService.prototype.nextPage = function () {
var fs = this;
if (fs.busy) return;
fs.busy = true;
fs.params.limit = fs.params.limit || _feedLimit;
if (fs.activities.length > 0)
fs.params.idLessThan = fs.activities[fs.activities.length - 1].id;
$http({ url: serviceBase + 'api/stream/getflatfeed', method: 'GET', params: fs.params })
.then(function (response) {
var feed = response.data;
console.dir(feed.results);
console.dir(fs.activities);
if (feed) {
fs.duration = feed.duration;
fs.gStreamMessage = feed.gStreamMessage;
fs.unread = feed.unread;
fs.unseen = feed.unseen;
fs.noMoreActivity = false;
if (response.data.results && response.data.results.length === 0)
fs.noMoreActivity = true;
else {
var acts = _decorateFeedActivities(response.data.results, fs.params);
acts.forEach(function (act) {
var alreadyExists = false;
fs.activities.forEach(function (e, i) {
if (e.id === act.id) {
console.log('alreadyExists!');
alreadyExists = true;
}
});
if (!alreadyExists) {
fs.activities.push(act);
}
});
};
}
fs.busy = false;
}.bind(this));
};
This is the directive used for activities:
feedModule.directive('feedCard', ['$compile', '$http', '$filter', function ($compile, $http, $filter) {
var getTemplate = function (contentType) {
var templateLoader,
baseUrl = 'app/areas/feed/cards/',
templateMap = {
donated: 'general-donation-card-tpl.html',
image: 'image-card-tpl.html',
video: 'video-card-tpl.html',
quote: 'quote-card-tpl.html',
link: 'link.html',
chat: 'chat.html',
audio: 'audio.html',
answer: 'answer.html'
};
var templateUrl = baseUrl + templateMap[contentType];
templateLoader = $http.get(templateUrl);
return templateLoader;
};
return {
restrict: 'E',
scope: {
activity: '=',
user: '='
},
replace: true,
link: linker
};
function linker(scope, element) {
var loader = getTemplate(scope.activity.verb);
var promise = loader.success(function (html) {
element.html(html);
}).then(function (response) {
element.replaceWith($compile(element.html())(scope));
console.log('---------------');
});
}
}]);
And this is the HTML for the infinite-scroll directive and the activities within:
<div class="infinite-scroll" infinite-scroll='feed.nextPage()' infinite-scroll-disabled='feed.busy || feed.noMoreActivity'>
<feed-card class="portlet light bordered feed-card message-card" ng-repeat="activity in feed.activities" activity="activity" user="data.user"></feed-card>
<div class="well" ng-show='feed.busy'>Loading data...</div>
<div class="well" ng-show='feed.noMoreActivity'>There is no more activity on your feed...</div>
</div>
I'm at a loss for what's happening. The additional, broken activities don't appear in any arrays of API returns. I would assume that it's maybe some sort of scoping issue that would cause the directive to fire twice, with one of them being broken?
If anyone has experienced anything like this, I would love to hear your advice. Thank you.
Fixed this by adding "ng-if='activity'" to the feed-card element.
i can't access to the cookies stored in localhost.
The cookis are already stored (view image)
When i try to display, i get undefined (view image)
Here is my js code for display :
var app = angular.module("Authentification", ['ngCookies']);
app.controller("log", ['$cookieStore', '$scope', '$http', function($cookieStore, $scope, $http) {
$scope.typeEmploye = $cookieStore.get('typeEmploye');
alert($scope.typeEmploye);
}]);
Here is my js code where i store the attribute in cookies after getting the result from my rest API.
var app = angular.module("Authentification", ['ngCookies']);
app.controller("main", ['$cookieStore', '$scope', '$http','$location',
function($cookieStore, $scope, $http, $location) {
$scope.user = [];
$scope.type=[];
$scope.auth = function() {
$http.get("/Employe/authentification?login=" + $scope.log + "&password=" + $scope.pw)
.success(function(data) {
console.log(data);
if (data) {
$scope.user = data;
$cookieStore.put('typeEmploye', $scope.user.type);
$cookieStore.put('Authentified',true);
$scope.type=$cookieStore.get('typeEmploye');
if($scope.type == "gerant"){
window.location.href = "/Gerant/index.html";
}
else if($scope.type == "cuisinier"){
window.location.href = "/Cuisinier/index.html";
}
else if($scope.type == "servant"){
window.location.href = "/Servant/index.html";
}
else{
window.location.href = "/error";
}
}
else{
alert("Login ou mot de passe incorrects");
}
}).error(function(data, status) {
alert("Problème dans le service d'authentification");
});
};
}]);
The information is stored in cookies. But, when i go to an other page ( with a different js file), i can't get the cookies. here is the js code.
var app = angular.module("ger", ['ngCookies']);
app.controller("main", ['$cookies', '$scope', '$http','$location',
function($cookies, $scope, $http, $location) {
var Type = $cookies.typeEmploye;
alert(Type);
}]);
I need to call the service variable in controller.
I tried to call $scope.userData1.data.name outside the Service function , it is undefined.
If I put {{userData1}} in template Messages Ctrl , it shows up all the data array including names.
I need to load the i-frame using the user_name variable.
angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;
return{
getData: function($http) {
return $http.get("http://www.website.com/index.php/id/user/call12").
success(function(response) {
/// console.log(JSON.stringify(response));
userData=response.data;
return userData;
}).error(function(data, status, headers, config) {
// log error
});
}
}
})
.controller('MessagesCtrl',function ($scope, Messages,$http,$ionicPopup,$timeout,$window,UserService,Outbox,$sce) {
$scope.userData1 = {}; // updated
$scope.myCtrl2= function(UserService,$http) {
UserService.getData($http).then(function(data) {
$scope.userData1 = data;
console.log($scope.userData1.data.name); // USERNAME exist
var name= $scope.userData1.data.name;
});
}
$scope.myCtrl2(UserService,$http);
var name= $scope.userData1.data.name; //undefined
$scope.formData4.upload_url = $sce.trustAsResourceUrl("http://www.website.com/index.php/id/user/view_form/"+ name);
})
template :
<form ng-controller="MessagesCtrl" ng-disabled="isRequesting">
<span class="item item-input" >
<span class="input-label"> </span>
<iframe id="iframe-123" src="{{formData4.upload_url}}" style="border: 0px none; height: 80px; margin: auto; width: 100%; overflow: hidden;" frameborder=0></iframe></span>
</form>
You got undefined because at this point, the answer (http.get) not yet return from the server.
You have to ensure this function $scope.myCtrl2(UserService,$http) received the answer asynchronous before you can call to the next line (var name= $scope.userData1.data.name;).
The best solution is to use promise - $q service like this:
.controller('MessagesCtrl',function ($scope, Messages,$http,$ionicPopup,$timeout,$window,UserService,Outbox,$sce,$q) {
$scope.userData1 = {}; // updated
$scope.myCtrl2= function(UserService, $http)
{
var deferred = $q.defer();
UserService.getData($http).then(function(data)
{
$scope.userData1 = data;
console.log($scope.userData1.data.name); // USERNAME exist
var name= $scope.userData1.data.name;
deferred.resolve();
});
return deferred.promise;
}
$scope.myCtrl2(UserService,$http).then(function(){
var name= $scope.userData1.data.name; //Now you got the answer!!!
$scope.formData4.upload_url = $sce.trustAsResourceUrl("http://www.website.com/index.php/id/user/view_form/"+ name);
});
})