I'm sad... I cook porridge of the ax..
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.
Related
I'm using ASP.NET MVC and AngularJS as my framework. I've a link which send request to MCV Action and finally gets forwarded to view. This view has registered JavaScript File which loads angular.element(document).ready(function (e){} function. Basically I'm trying to create a if else statement inside angular.element(document).ready. based on myparam=true. How can I do it?
Link -
"<h7>" + "" + "<a target=\"_blank\" href='/Submission/EditSubmissionFile?id=" + SubmissionID + "&myparam=true" +"'>" + "Add Attachment" + "</a><br></h7>" +
AngularJS Javascript File -
mainApp.controller('editSubmissionFileController', ['$scope', '$location', '$http', 'viewDataService', 'utilityService', '$window', 'constants', '$timeout', 'constants', 'adComplianceUtility', 'submissionRuleService',
function ($scope, $location, $http, viewDataService, utilityService, $window, constants, $timeout, constants, adComplianceUtility, submissionRuleService) {
angular.element(document).ready(function (e) {
// How to make this conditional based on parameter passed from Action or html link?
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
});
}
Action -
public ActionResult EditSubmissionFile(int id)
{
// We can only see what we are allowed
UserContext.TestSubmissionExists(id);
UserContext.TestSubmissionAccess(id, AccessRightEnum.ViewSubmissions);
var model = _submissionSvc.GetSubmissionViewModel(id);
return View("EditSubmissionFile", model);
}
Adding a simple window.location.href and check if parameter exists in URL does the job. Sometimes simple is better! Thank you.
angular.element(document).ready(function (e) {
// Check if URL contains a parameter value to restrict default pageload function.
if (window.location.href.indexOf("myparam=true") > -1)
{
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
}
});
I am just getting started with AngularJS. I'm coming from backend development, so this JavaScript is confusing for me. I followed the AngularJS tutorial and got the basics working.
I have a "record-list.component.js" file (Name derived from the AngularJS demo) which has a function to download data:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
})
This all works fine. However, I want to add another function that will call a URL so the backend can perform some magic. So I tried something like this:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://blackvue.tozz.nl/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
function DownloadFileController($file) {
$window.alert("Hi: " + $file);
}
})
This does not work. I tried a variety, such as controller: function, but nothing seems to work. Can someone point me into the good direction?
#Luiz Carlos his answer was correct! I got it working with the following code:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
this.DownloadFileController = function ($file) {
window.alert("Hi!");
}
}
})
And in HTML I can do:
<button ng-click="$ctrl.DownloadFileController()">Test</button>
Thanks!
I have ng-click producing a valid url from my data but struggling to get to open in a browser window, as this will trigger my 3rd party app to open.
I have tried some options and got a few extra button options(2-6) i have found on Stack and Google, can anyone help with getting it to open in a browser?
Here is an image of app showing the console output when I click on the full width button and the code in a Plunker.
http://i.imgur.com/0tfxTuE.jpg
https://plnkr.co/edit/WBYfa3m19MAwobtdbdfU
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tabs.home', {
url: '/home',
views: {
'home-tab' : {
templateUrl: 'templates/home.html'
}
}
})
.state('tabs.list', {
url: '/list',
views: {
'list-tab' : {
templateUrl: 'templates/list.html',
controller: 'ListController'
}
}
})
.state('tabs.detail', {
url: '/list/:aId',
views: {
'list-tab' : {
templateUrl: 'templates/detail.html',
controller: 'ListController'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/home');
})
.controller('ListController', ['$scope', '$http', '$state','$cordovaBluetoothSerial', '$location', function($scope, $http, $state, $cordovaBluetoothSerial, $location) {
$http.get('js/aboDATAONLY.json').success(function(data) {
$scope.orders = data;
$scope.whichorder = $state.params.aId;
})
function onPay() {
var itemsArr = [];
var invoice = {};
var myItems = {};
var myItem = {};
myItem['name'] = "Sphero";
myItem['description'] = "A robotic ball that can be controlled via apps";
myItem['quantity'] = "1.0";
myItem['unitPrice'] = "129.00";
myItem['taxRate'] = '0.0';
myItem['taxName'] = 'Tax';
itemsArr.push(myItem);
myItems['item'] = itemsArr;
invoice['itemList'] = myItems;
invoice['paymentTerms'] = 'DueOnReceipt';
invoice['currencyCode'] = 'GBP';
invoice['discountPercent'] = '0';
invoice['merchantEmail'] = 'myemail#mail.com';
invoice['payerEmail'] = 'foo#bar.com';
var returnUrl = 'http://wp1175175.wp220.webpack.hosteurope.de/speedhack/index.html';
var retUrl = encodeURIComponent(returnUrl + "?{result}?Type={Type}&InvoiceId={InvoiceId}&Tip={Tip}&Email={Email}&TxId={TxId}");
var pphereUrl = "paypalhere://takePayment/v2?returnUrl=" + retUrl;
//var pphereUrl = "paypalhere://takePayment/?";
pphereUrl = pphereUrl + "&accepted=cash,card,paypal";
pphereUrl = pphereUrl + "&step=choosePayment";
pphereUrl = pphereUrl + '&invoice=' + escape(JSON.stringify(invoice));
console.log(pphereUrl);
return pphereUrl;
}
$scope.pay = function () {
window.location = onPay();
};
}]);
give a try with
var url = onPay();
window.open(url , '_blank');
I am trying to bind from a http get request. The http get is returning true or false. I have tested the get and it is returning properly. When I run the code below, it shows the alert(1111) properly also. However, when I'm trying to change the button text, nothing appears! I have tried everything that I know to do. Any advice would be helpful.
Post.js
myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {
var status = "";
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
$scope.statusMessage = data;
} else {
//Following - show Follow
$scope.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}]);
Html
<span style="float: right" ng-controller="FollowController as follow">
<button type=" button" class="btn btn-success" onclick="location.href='#Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
{{ follow.statusMessage }}</button>
</span>
You should bind the variables to this instead of $scope as you are using controllerAs approach
Controller
myApp.controller('FollowController', ['$scope', '$http',
function($scope, $http) {
var status = "";
var follow = this;
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
follow.statusMessage = data;
} else {
//Following - show Follow
follow.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}
]);
I made a directive for automatically add links for a html validation, like that :
.directive('validationhtml', function($rootScope, $location) {
return {
restrict: 'A',
template: 'validation html',
controller: function($scope, $location) {
$scope.getUrl = function() {
var url = 'http://validator.w3.org/check?uri=' + $location.path;
console.log(url);
return url;
}
}
};
})
createTab(); is a function in rootscope, and correctly executed (new tab), but getUrl(); have a problem: the url is not good, in the return i have this
http://validator.w3.org/check?uri=function (c){if(B(c))return this[b];this[b]=a(c);this.$$compose();return this}
what's wrong ?
It should be location.path().
$location path is a function:
var url = 'http://validator.w3.org/check?uri=' + $location.path();