I need to call an AngularJS function call from javascript-side.
The below is the function I want to call from javascript.
https://github.com/aws-samples/aws-iot-examples/blob/master/mqttSample/js/app.js
AppController.$inject = ['$scope'];
AppController.prototype.createClient = function() {
var options = {
clientId : this.clientId,
endpoint: this.endpoint.toLowerCase(),
accessKey: this.accessKey,
secretKey: this.secretKey,
regionName: this.regionName
};
var client = this.clients.getClient(options);
if (!client.connected) {
client.connect(options);
}
};
My javascript
<body>
<div id='myid' class="container" ng-app="awsiot.sample" ng-controller="AppController as vm">
....
<div class="form-group">
<button class="btn btn-primary" id='myclick' ng-click="vm.createClient()" >Create Client</button> <-- working! -->
</div>
....
<script>
angular.element('#myid').scope().createClient(); // not working!
</script>
Can you help me?
try this:
angular.element(document.querySelector('#myid')).controller().info();
demo https://stackblitz.com/edit/angularjs-wxjhgd
you can tweak it to suit your needs
To call createClient() in angular is what I want to accomplish
Put the call in the $onInit function of the controller:
function AppController() {
this.$onInit = function() {
this.createClient();
});
}
For more information, see AngularJS $compile Service API Reference - Life-Cycle Hooks.
Related
i want execute a hello world function into a controller (call from html with button click), but i cant call this and i do not know why it does not work because not any show a error.
html code:
<html ng-app="app">
<div ng-controller="indexController">
<button type="button" ng-click="helloWorld()">action</button>
</div>
and controller js:
(function () {
'use stritct';
angular
.module('app',[])
.controller('indexController', indexController);
indexController.inject = ['$rootScope','$scope'];
function indexController($rootScope,$scope) {
var vm = this;
vm.helloWorld = helloWorld;
function helloWorld() {
console.log('hello');
}
}
})();
ng-click="helloWorld() will try to call $scope.helloWorld() function, that is undefined here.
helloWorld function is linked to your controller object, not to the Angular scope.
You have to set an alias of your controller, like ng-controller="indexController as index", and you will can call your helloWorld function like this: ng-click="index.helloWorld()".
To access functions or data in the template from your controller, you must define the function or value on the $scope object. Anything you define on the $scope object you can use in the template.
Instead of vm.helloWorld = helloWorld; try $scope.helloWorld = helloWorld;
In the same way, you can access data from your controller and display it in the template.
angular.module('app',[])
.controller('indexController', indexController);
indexController.$inject = ['$rootScope','$scope'];
function indexController($rootScope,$scope) {
$scope.helloWorld = function() {
console.log('hello');
}
$scope.message = 'From the controller!';
}
<html ng-app="app">
<body>
<div ng-controller="indexController">
<button type="button" ng-click="helloWorld()">action</button>
<p>{{ message }}</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
I use controller as approach instead of $scope. I have some problems with method calling from HTML. So, the question is that, how many ways exist in declare and call functions in this approach.
first: (If I want to do s.th. at first)
var vm= this ;
vm.dataOne=[];
function funcOne() {
myService.serviceFunc()
.then(function (response) {
vm.dataOne= response.data;
});
};
function activate() {
funcOne();
}
activate();
second: (If I want to initialize a variable based on a function returned value )
vm.dataTwo = function () {
doSomeThing();
}
Is there any way, too?
How should define a function in controller
which will be called from HTML, as
ng-click = "ctrl.dataTwo()";
Functions the way you've defined are private:
function functionOne() {
}; // Just function body, no need of semicolon
These are known as function declarations. Currently, they are only accessible within your controller.
To be able to call them, attach them to the controller so they become controller variables:
vm.functionOne = functionOne;
An advantage of this approach is that you can define functions after actually calling them, as opposed to how you do with $scope or $this. They are recognized via hoisting, and called.
About your initializing a returned value from a function, just call it:
vm.someVariable = someFunction();
Some references:
var functionName = function() {} vs function functionName() {}
Private Members in JavaScript
Angular Function Declarations, Function Expressions, and Readable Code
Angular Style Guide
First way using ng-controller="cntrl as vm" syntax:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
</div>
</body>
</html>
Second way using controllerAs as one of the attribute of directive:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.directive('customDir', function() {
return {
restrict: 'EA',
template: '<div>{{vm.name}}</div>',
controller: function(){
var vm = this;
vm.name = 'Custom Directive';
},
controllerAs: 'vm'
}
});
</script>
<body>
<div ng-app="MyApp">
<div custom-dir></div>
</div>
</body>
</html>
Way to calling a function with "controller as" syntax which is defined in controller but called in html:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MyCntrl', function($scope) {
var vm = this;
vm.name = 'Custom Directive';
vm.someFunction = function() {
vm.name = 'Button is Clicked!!!';
};
});
</script>
<body>
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
{{vm.name}}
<input type='button' ng-click="vm.someFunction()" value="Click" />
</div>
</body>
</html>
Other way, use function as constructor and add functionality to prototype
function Ctrl($window) {
this.$window = $window;
}
Ctrl.inject = ['$window']
Ctrl.prototype.click = function() {
this.$window.alert('clicked')
}
angular.module('app', [])
.controller('ctrl', Ctrl)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl as c'>
<button ng-click='c.click()'>Click me!</button>
</div>
I have a controller with such:
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
If next() (with ngClick) is called 3 times, we get:
//1
//2
//3
but if back() (with ngSwipeLeft) is called it returns
//-1
when I'm obviously expecting
//2
What am I missing here?
update: including ngTouch details - this seems to be the problem.. ngTouch is included.
When I watch the myVar value - its like it exists twice - one with the ngSwipeLeft call, and one with the ngClick call
Your snippet looks fine to me. You need to provide more code, error might be somewhere else. Look at the code below.
<!doctype html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-touch.min.js"></script>
<script>
var app = angular.module('myapp',['ngTouch']);
var controller = app.controller('mycontroller', ['$scope',function($scope){
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}]);
</script>
</head>
<body ng-controller="mycontroller">
<div>
<h1>MyVar: {{myVar}}!</h1>
<input type="button" value="back" ng-click="back()"/>
<input type="button" value="next" ng-click="next()"/>
</div>
</body>
</html>
Ok, so I've figured out my problem - I wasn't providing enough detail in the question - but if someone runs into something similar in the future, heres what was going on:
I was declaring my controller with ng-controller="myCtrl" in the templates, but also using routing, where I declared my controller like:
$routeProvider.when('/', {
templateUrl: 'myUrl.html',
controller: 'myCtrl'
});
This was instantiating the controller twice, and obviously causing problems (although that seemed to the only one to surface for now).
Removing the controller definition from the routing or the view did the trick.
need to see your html not sure about your problem, here is a sample working code,
<div ng-app="myapp">
<div ng-controller="IncDecController">
<span>current value is {{myVar}}</span>
<img src="https://angularjs.org/img/AngularJS-large.png" ng-swipe-left="back()"></img>
<button ng-click="next()">next</button>
</div>
</div>
script:
angular.module('myapp', ['ngTouch'])
.controller('IncDecController', ['$scope', function ($scope) {
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}])
I'm new to Angular JS. Sorry for this simple question.
I have learnt something from this tutorial: http://courseware.codeschool.com/shaping-up-with-angular-js/Slides/level01-05.pdf
And I have tried an example. This is not working. http://jsfiddle.net/89wfv/1/
HTML:
<html ng-app="main">
<body>
<div ng-controller="con">
<div>{{con.desc}}</div>
<input type='button' ng-click='getDesc();' value='Get name' />
</div>
</body>
</html>
Script
(function() {
var app = angular.module("main", []);
app.controller("con", function() {
this.desc = "test description";
this.getDesc = function() {
alert(this.desc);
}
});
})();
Problem is showing description in div and alert description by click.
Thanks in advance.
you forgot controller as something
<div ng-controller="con as ctrl">
<div>{{ctrl.desc}}</div>
<input type='button' ng-click='ctrl.getDesc();' value='Get name' />
</div>
take a look at the guide instead :
https://docs.angularjs.org/guide/controller
works:
http://jsfiddle.net/pYh89/
you didnt load angular correctly and add several syntax errors.
var app = angular.module("main", []);
app.controller("con", function () {
this.name = 'foo';
this.getName = function () {
alert("foo");
};
});
Angular JS is missing in your code please include it after downloading it.
<script src="angular.js"></script>
You can also use online version.
You forgot different things:
Here's a corrected JSfiddle:
http://jsfiddle.net/89wfv/2/
You have to:
Use $scope instead of this to reference to the data that is to be bound to the view, eg:
app.controller("con", function($scope) {
$scope.name = 'vasu';
$scope.getName = function() {
alert();
}
});
Put the script tag in Head
Not use the html tag, that could be overwritten by JSfiddle:
Do rather something like this:
<div ng-app="main">
<div ng-controller="con">
</div>
</div>
my first post on stackoverflow. (and english is not my native tongue).
I am trying to learn how to use emberjs.
It's not easy because of the lack of good tutorials.
So I decided to code a chat, I use nodejs and socket.io server-side.
Html
<script type="text/x-handlebars">
<div class="page">
<div class="users">
</div>
<div class="messagebox">
{{#view App.TextField valueBinding="currentMsg" placeholder="your message"}}{{/view}}
<button {{action "sendMsg"}}>Send</button>
</div>
<div id="chatbox">
{{#collection contentBinding="App.MsgsController" tagName="ul"}}
<b>{{value}}</b>
{{/collection}}
</div>
</div>
</script>
Javascript
var id;
var socketio = io.connect("127.0.0.1:8888");
socketio.on('id', function (data) {
id = data;
});
socketio.on("broadcast", function (data) {
if (id == data.id) {
return
}
App.MsgsController.addMsg(data.message);
});
socketio.on("own", function (data) {
App.MsgsController.addMsg(data.message);
});
App = Ember.Application.create();
App.Msg = Ember.Object.extend({
value: null
});
App.MsgsController = Ember.ArrayController.create({
content: [],
addMsg: function (value) {
var msg = App.Msg.create({
value: value
});
this.pushObject(msg);
}
});
App.TextField = Ember.TextField.extend({
insertNewline: function() {
this.get("controller").send("sendMsg");
}
});
App.ApplicationController = Ember.Controller.extend({
currentMsg: 't',
sendMsg: function () {
var currentMsg = this.get('currentMsg');
if(currentMsg) {
socketio.emit("message", { message: currentMsg, id: id});
this.set('currentMsg', '');
}
}
});
I want to focus App.TextField after the App.ApplicationController.sendMsg call.
I tried
App.TextField.$().focus()
but it seems that I can only use $() inside of its methods.
Someone can help me, please?
Edit :
Ok, I found the answer.
App.TextField is like "class", and the one on the view is an instance.
I must add an id in my view
{{#view App.TextField valueBinding="currentMsg" placeholder="your message" id="mytextfield"}}{{/view}}
and use jquery selector to access to the instance
$('#mytextfield').focus();
Use didInsertElement hook for the view to handle jquery methods.
http://emberjs.com/api/classes/Ember.View.html#event_didInsertElement