Need to bind the click events using Angular JS - angularjs

I am new in Angular JS. I have written a script that open a modal box. There are few buttons in that modal box on which I want to apply the click event.
Below I have mentioned my code:
angular.module("vss_shoppingcart_modal",["ui.bootstrap","dialogs","ngSanitize"]).controller("vss_shoppingcart_dialogService",function($scope,$dialogs,$sce){
$scope.init = function(){
dlg = $dialogs.create("/dialogs/whatsyourname.html","vssShoppingCartCTRL",{},{key: false,back: "static"});
};
}) // end dialogsServiceTest
.controller("vssShoppingCartCTRL",function($scope,$sce,$http,$modalInstance,data){
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data); // Apply the html to modal
});
$scope.cancel = function(){
$modalInstance.dismiss("canceled");
}; // end cancel
$scope.removeProduct = function(event){
$http({
method: "GET",
url: event.target.id
}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End removeProduct
$scope.updateQuantity = function(event){
$http({
method: "POST",
url: "' . $this->getUrl('shoppingcartpopup/index/updateCart') . '",
data: { "product_id": event.target.id, "qty": "2", "update_cart_action":"update_qty"}
}).
success(function(data, status, headers, config) {
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data);
});
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End updateQuantity
}) // end whatsYourNameCtrl
.run(["$templateCache",function($templateCache){
$templateCache.put("/dialogs/whatsyourname.html","<div class='ngModal' ng-bind-html='trustedHtml'></div>");
}]);// end run / module
On page load, I have passed a static block to modal window then by ajax request, I have updated the content again.
I don't know how to apply ng-click event on button in my view file.
In view, I have a link button -
<a href="javascript:void(0);" class="dialog-titlebar-close" role="button" ng-bind="cancel()" ng-click="cancel()">
<span class="header_close_icon">close</span>
</a>
ng-click is not working on this link.

Related

angularjs function not invoking mvc controller method

Hi I am trying to access my method through angularjs but when I click the button it hits the function but does not invoke the Controller actionresult but when I manually add the url in it then calls the method.
here is my angular code:
$http({ method: 'GET', url: '/Home/GetEmployeeList?=' + search }).
success(function (data, status, headers, config) {
$scope.customers = data;
}).
error(function (data, status, headers, config) {
alert('error');
});
}
and here is my controller:
public JsonResult GetEmployeeList(string search)
{
search = "Lourens";
List<Quotation> quote = new List<Quotation>();
using (SpecialHireEntities sp = new SpecialHireEntities())
{
var quotes = sp.Quotations.Where(x => x.ClientName == search).ToList();
return new JsonResult { Data = quotes, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
the url in the first line of JS should be
$http({ method: 'GET', url: '/Home/GetEmployeeList?search=' + search }).
rather than
$http({ method: 'GET', url: '/Home/GetEmployeeList?=' + search }).
With the code you mentioned, MVC model binding would never be able to find value for variable 'search' thus the request would not be resolved ending in an exception

Get data and after that routing

I want to make $http request, get results and according to data i get to route to view1 or view2. How can i do it in angular? Does somebody have example?
It should be some
$http({
url: 'API/v1/User/GetUserInfo',
method: "GET",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
//Something like this
var myVar=data.myVariable;
if(myVar==1){
$routeProvider.otherwise({ redirectTo: '/view1' });
}else{
$routeProvider.otherwise({ redirectTo: '/view2' });
}
}).error(function (data, status, headers, config) {
$scope.error = "There are problems with connection to server. Status:" + status + " Please, try to connect later.";
$scope.validationClass = "invalid";
});
and after that
Use to $location service to go to a specific path/route. Angular routing listens to changes on the location and will trigger all necessary actions.
if (myVar == 1) {
$location.url('/view1');
} else {
$location.url('/view2');
}

Cascading Dropdown Binding On Edit Click Angular

I want to bind dropdowns in edit mode but with value selected according to each record
My Edit View
<select ng-model="user.StateId" ng-init="user.StateId=#Model.StateId" data-ng-options="s.Id as s.State for s in States " data-ngchange="GetCities()"></select>
<select ng-model="user.CityId" data-ng-options="c.Id as c.City for c in Cities " ></select>
My Angular Js
function GetStates() {
$http({
method: 'Get',
url: '/Home/GetStates'
}).success(function (data, status, headers, config) {
$scope.States = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
$scope.GetCities = function (obj) {
var stateId = $scope.user.StateId;
alert(stateId);
if (stateId) {
$http({
method: 'POST',
url: '/Home/GetCities/',
data: JSON.stringify({ stateId: stateId })
}).success(function (data, status, headers, config) {
$scope.Cities = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states = null;
}
}
$scope.edit = function (user) {
var ref = user;
$http
({
method: 'GET',
dataType: 'html',
url: location.href = '../Home/Edit?Id=' + ref.Id,
})
}
Now when user click on edit i want to open user details in edit mode and i m doing so using $scope.edit user is my object in which i m getting data to edit now i want dropdown of edit view to show state and city selected as per the state and city i got as a response in function(user)

How can I track the start and end of a number of async processes with AngularJS?

I have a loading icon set up on my page that looks like this:
<div class="loading-mask"
data-ng-show="action != null">
<span>{{action}} ...</span>
</div>
When I set $scope.action to a message appears in the loading box.
When loading my page I have a number of different async processes that get data. For example I have:
getUserProfiles: function ($scope) {
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
and:
getSubjects: function ($scope) {
var url = '/api/Subject/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
How can I make it so that the first of these async processes causes a "Loading" message to appear and the last of the async process causes the loading box to not show any more. Note at this time I am not concerned about error messages. I just want the loading to not show when everything is completed.
To expand on what devmiles has said, but to handle the multiple asynchronous functions, you will want to set a loading flag on your first function to be called. I.e.:
getUserProfiles: function ($scope) {
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
And then you will want to wrap each of your asynchronous functions in a promise, like so:
getUserProfiles: function ($scope) {
var deferred = $q.defer();
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
deferred.reject();
});
return deferred;
},
You can then call $q.all on all of your asynchronous functions, and the success callback of this will occur once all asynchronous functions have resolved:
$q.all([getUserProfiles, getSubjects]).then(function() {
$scope.loading = false;
}
This means once all of your functions have resolved, loading will be set to false.
NB: If you want to access the data of your callbacks, you can pass it in as a parameter of "deferred.resolve(x)", and then in your $q.all callback, it will be available as function(x) { do something with x }.
Hope this helps!
EDIT: Don't forget to pass in angular's promise service, $q, to the controller where your functions are.
Just set some boolean flag on when your controller is being instantiated and reset this flag in your success/error functions.
.controller('MyCtrl', function ( $scope ) {
$scope.isLoading = true;
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
$scope.isLoading = false;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
$scope.isLoading = false;
});
});
Use ng-show with this flag to show your loading thingy.

How can I use ng-click to dynamically reload ng-repeat data?

I have a page that contains an ng-repeat directive. The ng-repeat works when the page first loads, but I want to be able to use ng-click to refresh the contents of the ng-repeat. I have tried the following code but it doesn't work. Any suggestions?
<div ng-click="loadItems('1')">Load 1st set of items</div>
<div ng-click="loadItems('2')">Load 2nd set of items</div>
...
<table>
<tr ng-repeat="item in items">>
// stuff
</tr>
</table>
ItemsCtrl:
$scope.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
I was hoping that my call to loadItems() would cause the ng-repeat directive to reload with the new data obtained from my server.
Add a broadcast in your callback and subscribe to it in your controller.
This should really be in a service btw
itemsService.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
$rootScope.$broadcast('updateItems', data);
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
In your controller:
$scope.$on("updateItems",function(d){
$scope.items = d;
});
So whenever you ng-click="update(id)"
$scope.update = function(id){
itemsService.loadItems(id);
}
Your items will automatically update because it is subscribed.

Resources