Why angularjs controller is not called when i click the button again? - angularjs

Hi i have a webpage like this,
left side has button,
right side is the area for ng-view (in my case, several checkboxes and submit button)
When i click the button, it'll
1. using the route provider, it'll reach its controller and template URL.
2. The controller will query some info from back end side (node.js)
3. The info above will be used by template URL to display initial checkbox options.
Now this procedure works fine for the 1st time. But when i click the button again, i was hoping it'll call its controller again, but from debugger, seems nothing happened, controller is not called.
So very confused, why is this please ???
in the server side,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var v1=0, v2=0;
var shellCmd = "... some executable ... ";
exec(shellCmd, function(error, stdout, stderr) {
if(error) {
console.log("Error running getting sid");
} else {
// get v1 and v2 from stdout
}
res.json( {"mystuff1":v1, "mystuff2":v2} );
});
app.post('/2setMyDiagValue', function(req, res)
{
// get the checkbox options from webpage,
// and save them in the backend
}
in the client side,
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/5MyDiag', {
templateUrl: 'partials/MyDiag.html',
controller: 'MyDiagController'
});
}
]);
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
// using http.get() to get existing my setting from server side
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself: MyDiag.html
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
index.html
<div class="container">
<a class="btn btn-md btn-info custom-btn" ng-href="#/5MyDiag">Diagnostics</a>
</div>
Since i need to remove company names in the variable, there might be mismatch, but idea is the same. Thank you for your help.

Talked with guru, it's supposed to be so, if angular feels no change to the web GUI, e.g. in my case, i clicked the same button twice, it won't call the route provider again for the 2nd click.
If you knew this concept, you don't need to read my code to answer this question.
Wish i can get the 4 points back.

Related

syncing variable across pages using angularJs

I have a html page with a link as follows:
<div ng-if="!adminCtrl.valid">
<div><a target="_blank" ng-href="https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri=http://localhost:8888/igSuccess.html&response_type=token">Authorize to Instagram</a><br/></div>
</div>
This goes to redirect page on success where the code is
<div ng-controller="AdminController">
<h2>You can close this tab/window</h2>
</div>
The control is same for both pages as follows:
app.controller('AdminController', ['$scope','$routeParams','$location', function($scope,$routeParams,$location){
var actrl = this;
actrl.valid = false;
var token = $location.absUrl();
if(token.indexOf('access_token') > -1){
console.log('found token so will do special');
actrl.valid = true;
$scope.$apply();
}
}}
I am expecting the link to disappear once the new page opens as i am updating the valid variable value.
i know the flaw seems to be the cross page communication. so how to deal with it?
Controllers are 'flushed' when you change views. To keep data from a view/controller to another, store your data within a Service.
UPDATE
controller:
app.controller('AdminController', [
'$scope', '$routeParams', '$location', 'ExampleService', function ($scope, $routeParams, $location, ExampleService) {
var actrl = this;
// Watches the service's value for changes and applies it to the controller
$scope.$watch(function(){return ExampleService.valid}, function(newValidValue){
actrl.valid = ExampleService.valid;
});
var token = $location.absUrl();
if (token.indexOf('access_token') > -1) {
console.log('found token so will do special');
ExampleService.valid = true;
// No need for this
// $scope.$apply();
}
}
}
Service:
app.service('ExampleService', [
function () {
//All properties here are kept through-out your app's life time
this.valid = false; // Init to false
}
}
To share data between Controllers in Angular JS, use a named Service to encapsulate the data. In your case, I would typically define an Auth service that provides a few methods for getting and setting the access_token for a user:
module.factory('Auth', function(){
return {
isValid: function(){ /* Check that a User is authenticated... */ },
setToken: function(token){ /* Store the token somewhere... */ },
getToken: function(){ /* Fetch the token from somewhere... */ }
};
});
To share data across "pages" -- tabs or windows in your browser -- even in a Single Page Application (SPA) like this, store the data in cookies or localStorage. You can use angular-local-storage by grevory (GitHub) to abstract the details of using localStorage with a cookie fall-back in non-compatible browsers.
The reason that one page cannot see the valid value defined in the other is because each page gets a separate instance of AdminController, each of which get their own separate instance of $scope tied to their respective DOM elements. Setting valid on the $scope of the redirect landing page has not effect on the completely detached $scope instance in the originating page.
You'd encounter similar difficulties with a trivial same-page example (CodePen):
angular.module('scope-example', [])
.controller('ExampleCtrl', function($scope) {
$scope.value = 'Initial Value';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form class="pure-form" ng-app="scope-example">
<fieldset ng-controller="ExampleCtrl">
First instance of <code>ExampleCtrl</code>:
<br>
<input ng-model="value">
<label>{{value}}</label>
</fieldset>
<fieldset ng-controller="ExampleCtrl">
Second instance of <code>ExampleCtrl</code>:
<br>
<input ng-model="value">
<label>{{value}}</label>
</fieldset>
<fieldset ng-controller="ExampleCtrl">
Third instance of <code>ExampleCtrl</code>:
<br>
<input ng-model="value">
<label>{{value}}</label>
</fieldset>
</form>
Even though each of the <fieldset> elements have identical ng-controller directives associated, each gets its own instance of ExampleCtrl and $scope, so the value property isn't shared between them. This holds true for any directive.

angular ng-repeat to always show even on empty object

Hi I want to post item to server, and with each successful addition, automatically add it to DOM with ng-repeat
<div class="" ng-repeat="book in books" >
<div id="eachBook">{{book.title}}</div>
</div>
to POST the data and also to upload an image file, I use Jquery ajax, and $state.go(".") to reload the current page:
var fd = new FormData();
fd.append("file", bookImage);
$http({
method: 'POST',
url: "/someurl,
data: fd,
headers: {
'Content-Type': undefined
}
}).success(function(Image){
var book_obj = {
bookTitle: bookTitle,
bookImage: Image._id
};
$http.post("url to owner book", book_obj)
.success(function(data){
$scope.bookImage = data.bookImage;
$timeout(function(){
alert("success", "successfully added your book");
$state.transitionTo('book', {}, { reload: true });
},2000);
})
})
The problem is with first addition, the DOM is still empty, and even though I use $state to reload the page, it still not working for the first addition. In the end I need to refresh the page manually by clicking refresh.
after the first addition, it works fine. With each book added, it automatically added to DOM..
Any idea how to automatically start the first one without manually rendering the page? using $timeout to delay the refresh has no effect.
Is it not just a simple post to list on success?
var app = angular.module('myApp', []);
app.controller('bookCtrl', function($scope, $http, $timeout) {
$scope.init = function(){
$scope.title = 'initial book?'
postBook();
};
$scope.books = [];
$scope.post = function() {
postBook();
};
function postBook(){
if (!$scope.title) return;
// timeout to simulate server post
$timeout(function() {
$scope.books.push({title:$scope.title});
$scope.title = null;
}, 1000);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="bookCtrl" ng-init="init()">
<div class="" ng-repeat="book in books">
<div class="eachBook">{{book.title}}</div>
</div>
<input type="text" ng-model="title" /><button ng-click="post()">save</button>
</div>
EDIT: Not sure why your DOM isn't ready but how about ng-init to accomplish an initial book post?

Angular Nested Controller Data access

I don't know how to access the data from a nested ( child ) controller.
<form ng-controller="TestController as test" ng-submit="submit()">
<h5>Employee name :</h5>
<div ng-controller="mainCtrl" class="row-fluid">
<form class="row-fluid">
<div class="container-fluid">
<input type="text" ng-model="name" typeahead="name for name in names | filter:$viewValue" />
</div>
</form>
</div>
<h5>Comment : </h5>
<textarea ng-model="test.test_content"></textarea>
<input type="submit" id="submit" value="Submit" />
</form>
As you can see i have 2 controllers.The main one is a form , the second one is an input box that allows the user to search the name in a list using typeahead.
I want to be able to acces the content of ng-model="name" in my child controller (mainctrl) in my TestController.
I've tried to access it directly with $scope.name but it doesn't work.
I've also tried test.name as the ng-model and it didn't work either.
I'm sending the data of my TestController to my server and would like to send the data ( name ) from my mainCtrl aswell, directly from TestController. So that when my user click submit it send both the name + the test_content in $http.post request.
Anyone know how to do that ?
Thanks
I've found this but it didn't really help.. https://fdietz.github.io/recipes-with-angular-js/controllers/sharing-models-between-nested-controllers.html
edit:
my search controller
.controller("mainCtrl", function ($scope, $http) {
$scope.selected = '';
$http.get('/feedbacks/search.json').
then(function(response) {
$scope.succes = " ok "
$scope.names = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = " error"
});
});
my form controller :
angular.module('FeedbackTool')
.controller('TestController',['$scope', '$http', function($scope,$http) {
$http.get('/feedbacks.json').
then(function(response) {
$scope.succes = " ok "
$scope.list = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = " error"
});
$scope.submit = function() {
$http.post('/feedbacks.json', { data:this.test }).
then(function(response) {
$scope.succes = 'sent';
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.succes = 'fail';
});
};
}]);
The parent scope is accessible from within the child scope, but the child scope is not accessible from the parent. Typically the way to deal with this is to assign values from the child scope to properties already defined in the parent. In your case I think you just need to use test.name as the ng-model expression.

Not able to load $http.get - JSON data in ui tabset child tabs

I tried to load a dropdown with the response got from http post. But its failing to load on child tabs.
When i click next button from tab1. I make a post call and get a JSON back. Using the returned data i want to load a dropdown in my second tab.
I already raised a query on tabset and it worked fine. Now I modified the plunker little bit. I did the same way mentioned in the below link. But i'm missing something when i try to do the samething with $http.get
Tabset $rootScope scope not updating
app.js
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope, $http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common.tabData;
});
Html
<tabset ng-init="steps={step1:true, step2:false}">
<tab heading="Step 1" active="steps.step1">
<div data-ng-controller="SampleController">
<form data-ng-submit="submitTab1()">
<label>Some Operations ...</label>
<br>
<br>
<label>Click next to retrieve json from server ...</label>
<button type="submit">Click Next</button>
</form>
</div>
</tab>
<tab heading="Step 2" active="steps.step2">
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList">
<option value="">--- select ---</option>
</select>
</form>
</div>
</tab>
</tabset>
Post.json
[
{
"id": 1,
"title": "Arnold"
},
{
"id": 2,
"title": "stallone"
}
]
Plunker Code http://plnkr.co/edit/EZC1d6tDDZlpWZUHY6os?p=preview
Your issue has nothing to do with loading from http, but it has to do with properly copying reference of objects.
When you do $scope.userList = Common.tabData; the reference of tabData is copied to userList, and then when the tabData is updated using Common.tabData = data now tabData in the service points to a different reference and $scope.userList keeps pointing to the old one. So instead of getting the reference of tabData and copying it to the userList, set up the service object itself on the scope.
In your controller change $scope.userList = Common.tabData to $scope.userList = Common :-
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and in the view iterate upon userList.tabData
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
Plnkr
If I modified your code this way it works
1) changed tabData to be an array
2) Used angular.copy instead of asignning
.service('Common', function() {
this.tabData = []; ==> Changed this to array
})
$http.get("post.json", {
// Some logic
}).success(function(data) {
angular.copy(data,Common.tabData); ==> Used angular copy so it copies the array
$scope.steps.step2 = true;
});
Updated Plnkr
main issue in your code is controller get executed first and then Common.tabData is loaded.so can do like this:
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope,$http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and html code according to this is:
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
<option value="">--- select ---</option>
</select>
</form>
</div>

Angularjs change view without a click

I am stil new to Angular, but trying, very hard, to get my head round it.
Basically, I just want to move from one view, to another one function is complete. Here is the code:
App.controller('clientLogin', function ($scope, $http, $route) {
$scope.clientLoginBt = function () {
var sun = $('#ClientUsername').val();
var spa = $('#ClientPassword').val()
$http({url: "/sources/",
headers: {"X-Appery-Database-Id": dbid},
params: {where: '{"$and" : [{"username": "' + sun + '"}, {"password" : "' + spa + '"}]}'}})
.success(function (data) {
console.log(data.length);
$scope.clientLogggedin = data;
if (data.length > 0) {
$route.clientLogggedin();
} else {
}
})
.error(function (status) {
console.log('data on fail: ' + status);
});
}
});
Above, if the data comes back with more than one row, the user log is correct, and I just want to change view!
I have tried $location, did not work, and as Angular is really simple to use, in the amount of coding, I cannot see any info on it, other than if you click, it starts a controller.
Here is the HTML:
<div class="row" ng-controller="clientLogin">
<div class="large-12 medium-12">
<input type="text" id="ClientUsername" placeholder="Enter Username" />
<input type="password" id="ClientPassword" placeholder="Enter Password" />
<button ng-click="clientLoginBt()">Login</button>
</div>
</div>
The page I am looking to jump to, within the is called clientLoggedIn.html.
I have also added it to the config, thinking i could access it with $route :
App.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'views/home.html'
})
.when('/userLogin', {
templateUrl : 'views/userLogin.html',
controller: 'userLoginController'
})
.when('/clientLogin', {
templateUrl : 'views/clientLogin.html',
controller: 'clientLoginController'
})
.when('/clientLoggedIn', {
templateUrl : 'views/clientLoggedIn.html',
controller: 'clientLoggedInController'
})
.otherwise({
redirectTo : '/'
}
);
});
Any ideas on what I am doing wrong please ?
Thanks in advance.
Using path method of $location should do the trick. Since you want to get to clientLoggedIn.html, you would need to use the matching route (/clientLoggedIn):
$location.path("/clientLoggedIn");
Be sure that $location service is injected into your App Controller. This is the line you should probably replace with what I have above:
$route.clientLogggedin();
It is just a matter of checking an indicator whether the $http call was successful or not. If you are not willing to add a routing for clientLoggedIn.html. You can do something like below, just to enable the logged in page:
<div class="row" ng-controller="clientLogin">
<div class="large-12 medium-12" ng-hide="sucessfulLogin">
<input type="text" id="ClientUsername" placeholder="Enter Username" />
<input type="password" id="ClientPassword" placeholder="Enter Password"/>
<button ng-click="clientLoginBt()">Login</button>
</div>
<ng-include src="'views/clientLoggedIn.html'" ng-show="sucessfulLogin">
</ng-include>
<!-- or just include the DOM element here if you do not
want a separate html altogether-->
</div>
and in the REST call:
if (data.length > 0) {
//Assuming the flag in pre-initialized to false in controller
$scope.sucessfulLogin = true;
} else {
}
Also note, using ng-include directive you can still use a separate controller in clientLoggedIn.html if you are willing to. Just have to use ng-controller in the first element inside clientLoggedIn.html.

Resources