Calling the callService function fails. Instead none of my console messages are showing in the console except for 'making a controller....'. I'm using the directive ng-click="callService()" to make the call from an HTML button. I'm new to angular, can someone point me in the right direction? Code is below.
(function() {
console.log('making a controller....');
'use strict';
angular.module('myModule').controller('myController', myController);
myController.$inject = ['$scope','$http'];
function myController($scope, $http) {
console.log("controller initialized...");
$scope.callService = function(){
console.log("callService called...");
var urlSearchService = 'http://domain/proj/rs/stuff/moreStuff';
var skuVal = $scope.skuField;
var mVenVal = $scope.mVendorField;
//need to somehow specifiy that xml is a #FormParam
var xmlItemSearchRequest = "<ItemSearchRequest>"
+"<skuid>" + skuVal + "</skuid>"
+"<mvendor>" + mVenVal + "</mvendor>"
+"</ItemSearchRequest>";
console.log('calling: ' + urlSearchService + 'sending xml: ' + xmlItemSearchRequest);
$http.post(urlSearchService, xmlItemSearchRequest).
success(function(data){
$scope.searchResults = data;
console.log('call to ' + urlSearchService + ", was a success.");
}).error(function(data, status) {
console.error('Calling error', status, data);
});
};
};
})();
You are declaring the callService function inside the scope of the controller function, so it won't be accessible from the $scope. You need to add it to the $scope in order to be able to use it in your templates.
Instead of:
var callService = function(){
Do:
$scope.callService = function(){
As per your latest comment, you are not binding correctly the controller.
This:
<div data-ng-controller="inventorySearchController"><input type="button" class="btn btn-primary btn-lg" ng-click="callService()" value="Search" /></div> –
Should be:
<div data-ng-controller="myController"><input type="button" class="btn btn-primary btn-lg" ng-click="callService()" value="Search" /></div> –
Related
When I load the html page, my controller retrieves data from an API end point regarding a course. The page gets populate with the data about the course. But at the same time I want to populate part of the page with data about the lecturer of the course (their image, name , description etc ...). I pass the lecturer name to the method using the ng-init directive but I get a
ReferenceError: lecturerFac is not defined.
I am not sure but I believe the issue is the way I am calling the getLecturer() function using the ng-init directive.
What I want to happen when the page loads is have the Lecturer's details displayed on the page along with the course details.
courses.html
<div class="container" ng-controller="CoursesDetailsCtrl">
<div class="row" >
<div class="col-4" ng-model="getLecturer(courses.lecturer)">
<div>
<h3>{{lecturer.name}}</h3>
<<div>
<img class="img-circle" ng-src="{{lecturer.picture}}" alt="" />
</div>
<p>{{lecturer.description}}</p> -->
</div>
</div>
<div class="col-8">
<div class="myContainer" >
<h2>{{courses.name}}</h2>
<div class="thumbnail">
<img ng-src="{{courses.picture}}" alt="" />
</div>
<div>
<p>{{courses.description}}</p>
</div>
</div>
</div>
</div>
</div>
CoursesDetailsCtrl
todoApp.controller('CoursesDetailsCtrl', ['coursesFac','lecturerFac','$scope','$stateParams', function CoursesCtrl(coursesFac, lecturerFac, $scope, $stateParams){
$scope.getLecturer = function(name){
lecturerFac.getLecturerByName(name)
.then(function (response) {
$scope.lecturer = response.data;
console.log($scope.lecturer);
}, function (error) {
$scope.status = 'Unable to load lecturer data: ' + error.message;
console.log($scope.status);
});
};
}]);
lecturerFac
todoApp.factory('lecturerFac', ['$http', function($http) {
var urlBase = '/api/lecturer';
var coursesFac = {};
lecturerFac.getLecturer = function () {
return $http.get(urlBase);
};
lecturerFac.getLecturerByName = function (name) {
return $http.get(urlBase + '/' + name);
};
return lecturerFac;
}]);
todoApp.factory('lecturerFac', ['$http', function($http) {
var urlBase = '/api/lecturer';
var coursesFac = {};
var service = {};
service.getLecturer = function () {
return $http.get(urlBase);
};
service.getLecturerByName = function (name) {
return $http.get(urlBase + '/' + name);
};
return service;
}]);
i Think the cause of this error is the lecturerFac variable is not initialize in the factory. Create an empty object call lecturerFac in the factory and return it.
todoApp.factory('lecturerFac', ['$http', function($http) {
var urlBase = '/api/lecturer';
var coursesFac = {};
var lecturerFac= {};/////////////////////
lecturerFac.getLecturer = function() {
return $http.get(urlBase);
};
lecturerFac.getLecturerByName = function(name) {
return $http.get(urlBase + '/' + name);
};
return lecturerFac;
}]);
Also avoid calling functions inside the ng-model. When you bind something with ng-model it must be available for both reading and writing - e.g. a property/field on an object. use ng init instead
I am adding Social Logins to my web app. Now I do a get on our webapi to get the available logins and then use an ng-repeat to list the buttons.
I have the following service;
var _getExternalProviders = function () {
var returnUrl = "#";
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogins?returnurl=" + returnUrl
+ "&generateState=true";
return $http.get(externalProviderUrl).then(function (results) {
return results;
});
};
i then call this service from my controller;
authService.getExternalProviders().then(function (results) {
$scope.externalProviders = results.data;
},
function (err) {
$scope.message = err.error_description;
});
and my view is as follows;
<div data-ng-controller="loginController">
<div data-ng-repeat="provider in externalProviders">
<button class="btn btn-large btn-{{provider.name.toLowerCase() == 'microsoft' ? 'windows' : provider.name.toLowerCase()}} btn-block" type="button" data-ng-click="authExternalProvider('{{provider.name}}')"><i class="fa fa-{{provider.name.toLowerCase() == 'microsoft' ? 'windows' : provider.name.toLowerCase()}}"></i> | Connect with {{provider.name}}</button>
</div>
</div>
(which is added to the parent view using an ng-include)
<div ng-include="'app/views/externalProviders.html'">
</div>
Now this is working and the buttons are returning and rendering great, and when I inspect the html
data-ng-click="authExternalProvider('{{provider.name}}')"
is rendering as
data-ng-click="authExternalProvider('Google')"
for example, however when i click the element the function is being passed '{{provider.name}}' as a string instead.
The cothroller method for the ng-click is as follows;
$scope.authExternalProvider = function (provider) {
console.log(provider);
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
Can anyone tell me what I am doing wrong please?
data-ng-click="authExternalProvider('{{provider.name}}')"
gets interpreted as JavaScript so what you really want is
data-ng-click="authExternalProvider(provider.name)"
My controller is defined as :
broConsoleApp.controller('actionCreateController', ['$scope', '$stateParams', '$sce', function ($scope, $stateParams, $sce) {
$scope.html = "";
var resp = [];
var params = {};
/* lot of other things here */
$scope.getHtml = function (type) {
$scope.html = "";
$.get(apiHost + "/action/type/defn/" + type).success(function (response) {
resp = response['RESPONSE']['ActionsParams']['param'];
console.log(resp);
if (resp instanceof Array) {
resp.forEach(function (entry) {
$scope.html = $scope.html + $.hbs("/web/templates/actionCreate.hbs", entry);
});
}
else
$scope.html = $scope.html = $scope.html + $.hbs("/web/templates/actionCreate.hbs", resp);
$scope.$apply(function () {
$scope.html = $sce.trustAsHtml($scope.html);
});
})
.error(function (jqXHR, textStatus, errorThrown) {
console.log("Failed to fetch XML.")
});
};
$scope.add = function(){
console.log(" entered add ...");
var $key = $("<input type='text' class='input-small form-control' placeholder='Key'>");
var $value = $("<input type='text' class='input-small form-control' placeholder='Value'>");
$('form #'+name).append($key);
$('form #'+name).append($value);
};
}]);
My get HTML function gets all the HTML and renders it against a JSON . My .hbs file looks like :
{{#if_eq type "MAP_VALUED"}}
<div class="col-lg-10 col-lg-offset-1 MAP_VALUED" id="{{name}}">
<label class="control-label col-lg-3">{{label}}</label>
<form class="col-lg-9 controls form-inline">
<input type="text" class="input-small form-control" placeholder="Key">
<input type="text" class="input-small form-control" placeholder="Value">
<button type="button" class="btn btn-primary pull-right" ng-click="add()">+</button>
</form>
<br><br>
</div>
{{/if_eq}}
Here I want an onClick action to call the method $scope.add() defined in the controller. The ' + ' button adds new key value forms basically.
I am binding this rendered HTML as :
<div ng-app="broConsoleApp" ng-controller="actionCreateController">
<div ng-bind-html="html"></div>
</div>
Since the rendered HTML ultimately is defined under broConsoleApp , the ng-cick should work right? Well it is not working. Can someone help me out here. Even if I use a jquery method onClick or something how do I do so without creating a new file. I want it to be in my controller.
Been stuck since morning.
Please check working example : https://jsfiddle.net/Shital_D/oyx0fd6e/3/
HTML
<div ng-app="broConsoleApp" ng-controller="actionCreateController">
<div compile="html"></div>
</div>
Create directive
app.directive('compile', function ($compile) {
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
return scope.$eval(attrs.compile);
},
function (value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
});
And
Controller
app.controller('myController', function ($scope, $compile) {
$scope.html ='<div><button ng-click="callMe()">clickme</button><div>';
});
I'm using typeahead to get some suggestions on an input text, this is inside a div controlled by an Angular controller.
The code for the suggestion tasks works with a jQuery plugin, so when I select, something I'm trying to assign a value to $scope, however this is NEVER happening.
I already tried getting the scope of the element with var scope = angular.element($("#providersSearchInput").scope() and then assign it as suggested here but it didn't work.
This is what I'm trying:
<div class="modal-body" ng-controller="ProvidersController" ng-init="orderReviewTab = 'observations'">
<input type="text" id="providersSearchInput" data-provide="typeahead" class="form-control input-md" placeholder="Buscar proovedores">
{{currentProvider}}
</div>
The controller looks like this:
tv3App.controller('ProvidersController', function($scope, $rootScope, $http, $timeout) {
var resultsCache = [];
$("#providersSearchInput").typeahead({
source: function (query, process) {
return $.get("/search/providers/?query=" + query, function (results) {
resultsCache = results;
return process(results);
},'json');
},
matcher: function (item) {
var name = item.name.toLowerCase();
var email = item.email.toLowerCase();
var contact_name = item.contact_name.toLowerCase();
//console.log(name);
var q = this.query.toLowerCase();
return (name.indexOf(q) != -1 || email.indexOf(q) != -1 || contact_name.indexOf(q) != -1);
},
scrollHeight: 20,
highlighter: function (itemName) {
var selected = _.find(resultsCache,{name:itemName});
var div = $('<div></div>');
var name = $('<span ></span>').html('<strong style="font-weight:bold">Empresa: </strong> ' + selected.name);
var contact = $('<span ></span>').html(' <strong style="font-weight:bold">Contacto: </strong> ' + selected.contact_name);
var email = $('<span ></span>').html(' <strong style="font-weight:bold">e-mail:</strong> ' + selected.email);
return $(div).append(name).append(contact).append(email).html();
},
minLength: 3,
items: 15,
afterSelect: function (item) {
console.log(item);
$scope.$emit('providerSelected',item);
}
});
$scope.$on('providerSelected', function (event,provider) {
console.log(provider);
$scope.currentProvider = provider;
$scope.$apply();
});
});
Edit
I tried this to check any changes:
$scope.$watch('currentProvider',function (newValue,oldValue) {
console.log(oldValue);
console.log(newValue);
});
So when selecting something it actually triggers and $scope.currentProvider seems to be updated but its never getting rendered at view ...
get https://angular-ui.github.io/bootstrap/
once you do, in your code make sure
angular.module('myModule', ['ui.bootstrap']);
and for typeahead have
<input type="text" ng-model="currentProvider" typeahead="provider for provider in getProviders($viewValue) | limitTo:8" class="form-control">
In your controller make sure you have
$scope.getProviders = function(val){
return $http.get('/search/providers/?query=' + val).then(function(response){
return response.data;
})
}
This should do the trick although I haven't tested
I generate modal forms using function function makeModalEnroll(name, description, i, id)
And in one of my lines there is a string
modal += '<button type="button" id="enroll' + i + '" class="btn btn-success" data-dismiss="modal" onclick="send(this.id);"> Enroll <span class="glyphicon glyphicon-arrow-right"></span> </button>';
I've got function send and for now I submit form with id = 0
function send(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};
But browser says that ReferenceError: send is not defined.
I tried to put function send before and after function makeModalEnroll but this error is always occurs.
How to solve this problem?
May be you don't expose your function to the global scope, try this:
window.send = function(id) {
alert(id);
var c = id.charAt(id.length - 1);
alert(c);
$('#enrollForm0').ajaxSubmit({url: 'enroll.html', type: 'post'});
};