I have two controller's and I want to call other parent controller function with parameter when user clicks the button.
Html
<a ng-click='test('something')'>Click</a>
Controller
controller: function($scope) {
..........
$scope.test= $scope.$parent.parentTest(t);// it fails...
..........}
Parent Controller
$scope.parentTest= function(m) {
var my=m;
...Something...
}
If I run function without any parameter, it works. If I run the function with parameter it doesn't.
I want to call parent function with parameter.
The mistake in your code is with this line:
//This assigns the RESULT of parentTest() to $scope.test
$scope.test= $scope.$parent.parentTest(t);
// Either of the 2 options below will probably work for you.
//This assigns the parentTest Function itself to $scope.test
$scope.test= $scope.$parent.parentTest;
//This wraps it safely in case the parentTest function isn't ready when
// this controller initializes
$scope.test= function(t){$scope.$parent.parentTest(t)}; // << Change it to this!
Check this plunkr, maybe this can help you
plunkr
access parentfunction in child controller
Related
I have a client who is based in china and requires specialised captcha that works there. The captcha I need to use is here https://open.captcha.qq.com/
Basically there are 4 steps to get it working:
In the label of html, add this line:
<script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
Add id and property to any DOM element that we want to activate captcha, such as button, div or span. Sample code as below:
<button id="TencentCaptcha"
data-appid="2090807227"
data-cbfn="callback"
>验证</button>
Then create callback function in javascript:
function callback(res){
console.log(res)
if(res.ret == 0){
alert(res.ticket) // ticket
}
}
From the callback, make a POST request to the server to validate the ticket
I'm struggling this to incorporate this into my UI which uses Angular 1.5.6.
My controller is:
.controller('MyCtrl', function($scope) {
$scope.oldCallback = function(){
console.log('in the old callback');
};
$scope.newCallback = function(){
// PASS THIS AS THE CALLBACK TO NEW REGISTER BUTTON
};
})
I have created a CodePen here.
The only way I can get it remotely working is if I pass in a method in the HTML e.g.
<button type="submit" id="TencentCaptcha"
data-appid="2090807227"
data-cbfn="(function(res){alert('res is ' + res)})">
Register
</button>
After clicking Register, the captcha library presents a popup with a challenge to the user. Once completed, the callback passed to data-cbfn is executed. How can I call my controller method from this callback, passing through the result?
I created a global function and was then able to call the correct method in the controller:
function callback(){
var scope = angular.element(document.getElementById("home")).scope();
scope.register();
}
You could also add your function to the window from your angular controller:
.controller('MyCtrl', function($scope, $window) {
$window.callback = function callback(res) {
$scope.register();
};
});
This way you don't have to request the document element which may change scope or id later on.
Also: $compileProvider.debugInfoEnabled(false); will actually disable the functionality to retrieve the scope from a document element like you've done.
You should be turning off the debugInfo functionality in production mode for performance and security reasons.
With jQuery I can pass params to trigger event and get them from a function. Like this:
$('div').trigger('click', [1])
$('.classname').live('click', function (event, param) {
alert(param);
});
Can I catch the same param using ng-click?
simple answer
yes you can like this
<button ng-click="yourtask(task.id)">remove</button>
where task is the scope and id is part of that scope.
Yes, but doesn't look like this.
In angular you must configure the ngClick directive with a function of your $scope that can receive paramenters like so:
Controller
function myController($scope){
$scope.myClickHandler = function(param){
console.log(param);
//code here
};
}
Html
<button ng-click="myClickHandler('foo')">Click</button>
if you need to trigger this function handler it can be invoked like a normal function.
On controllers:
$scope.myClickHandler('bar');
On views (once your view in on myController scope):
myClickHandler('bar');
I am trying to follow style guide for angular and there wrote we should use this insted scope...
Styleguide
Could someone explain me when I am able to use this?
Here is my try..... What I am doing wrong?
I am trying to toggle form....
here is my html code:
REPLY
<a href="#" ng-click="formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>
With classic $scope I would do like this inside my conroller :
$scope.formEdit = function(data){
data.formEditShow = !data.formEditShow;
}
But with this it should look something like this(but don't work):
var vm = this;
vm.formEdit = formEdit;
function formEdit(data){
data.formEditShow = !data.formEditShow;
}
Anyone can help me to understand this?
When you are using this(context) in controller instead of $scope, you must use controllerAs while defining html on page to access controller variables. Whenever you wanted to use variable bounded to this on view you could use alias of your controller. Below you can see vm is alias of controller.
ng-controller="myController as vm"
Then while accessing controller method an variable inside ng-controller div you need to use alias of your controller like ng-click="vm.formEdit(x)"
HTML
REPLY
<a href="#" ng-click="vm.formEdit(x)" ng-if="x.formEditShow" >CLOSE</a>
Assuming your controller is named FormController.
First step
The first step is to declare the route (or the ng-controller value if you are not using a router) as such:
FormController as form // name it semantically instead of a generic name
Due to the above configuration, angular will alias as form the instances of FormController.
HTML template
Then adapt your html template according to the alias you gave (form). I modified your html to keep only the essential part about the question. We are calling the functions form.reply and form.close.
REPLY
CLOSE
Controller declaration
According to what we wrote above, our controller should look like that:
myApp.controller('FormController', function () {
var vm = this;
vm.reply = function () {
// ...
}
vm.close = function () {
// ...
}
}
Notice the var vm = this; line? Theoretically we could get rid of this line, and store the functions reply and close in the this object. But depending of the context, this does not refer to the same object. In a callback function this would not refer to the controller but to the callback function. That's why we are caching the this that refers to the controller. We usually name this reference vm for viewmodel, as a controller controls a view.
My problem is I need "det" value applied to the controller and reload it.
Anyway nevermind it and continue reading first so you will understand my question.
I have this controller below.
At first load, the xxx isn't going to exist in the object then det value will be null. So it is expected that the controller's service will have an error telling that it can't be find. (See Controller code below)
However, when I click a button on my page (buttons html code is not here, I don't think it is necessary), it fills the object in and I'm wishing to reload the controller so I will see my expected output.
The HTML below is the one who loads the controller, what I'm expecting is that the
data-ng-model="{{$parent.$root.ParentItems['xxx'].xxx}}" will update the xxx value in controller. And it actually does because I'm using "<span>{{$parent.$root.ParentItems['xxx'].detnumber}}</span>" to test it.
Now, again,
My problem is I need the "det" value applied to the controller and reload it.
What I'm thinking is to create a new controller but I will just repeat the code.
//html
<div data-ng-switch-when="thisIsIt" ControllerOne data-ng-model="{{$parent.$root.ParentItems['xxx'].xxx}}"></div>
<span>{{$parent.$root.ParentItems['xxx'].xxx}}</span>
//Attribute ControllerOne
controller: function ($scope, $element, $http) {
function par() {
var xxx= null;
xxx = $scope.$parent.$root.ParentItems['xxx'].xxx;
var det = { xxx: xxx};
return det;
}
$http.post('/api/values/entries/GoHere', par()).success(function (salData) {
var buildSHGraph = function (shData) {
//code code codes...
}
$scope.Array1 = [];
angular.forEach(salData, function (evt) {
//Code Code Codes
});
buildSHGraph($scope.Array1);
});
}
I thing you can use $rootScope and pass your value to it. Then the value can be accessible globally by your application.
When your value is downloaded from ajax, the scope/html will be updated.
When you define variable with 'var xxx' cannot access it outside of the scope of this function, in your case 'par'.
function par() {
this.xxx = null;
this.xxx = $scope.$parent.$root.ParentItems['xxx'].xxx;
}
When you try to change view from callback from async task such as $http.post you need to '$digest' or '$apply' the scope
//Do this in success callback function in your ajax request
$timeout(function() { //$timeout must be setup as dependency in constructor such as $scope and $http
$scope.$digest();
});
I have a controller that seems to be misbehaving. I have removed all the other code that works to make this short:
Controller:
'use strict';
angular.module('AppliedSiteApp').controller('CarouselCtrl', function ($scope) {
$scope.nextImage = function() {
console.log('hi');
}
});
View:
<div class="carousel" ng-controller="CarouselCtrl">
<ul class="nav">
<li ng-click="prevImage()"><</li>
<li ng-click="nextImage()">></li>
</ul>
</div>
Every time I click the button in the browser it says: 'TypeError: object is not a function' or 'no method replace'. What am I doing wrong?
Are you still having a problem with this?
I ran into the same issue. The problem for me was that the function name in the controller and view was the same name as a form I was using in the same view.
Changing either the form name or the function name fixed the error for me.
Something is wrong with the way you are wiring things I believe. I usually use this scaffold:
angular.module('AppliedSiteApp.controllers', []).
controller('CarouselCtrl', ['$scope', function($scope) {
$scope.nextImage = function() {
console.log('hi');
}
}]);
The first argument to controller is the name, and the second is an array. In the array, you define what services you are injecting into your controller, then you define the callback function with the injected services as parameters.
When creating a new module you need to specify a second parameter (its dependencies). If you have none, simply pass an empty array.
angular.module('AppliedSiteApp', [])...
Your example could access an existing module (that's when you don't specify the second argument), but then there's probably some code missing to spot the error (or I'm just blind).
try the following definition of controller
var AppliedSiteApp = angular.module('AppliedSiteApp', []);
function CarouselCtrl($scope) {
$scope.nextImage = function() {
console.log('hi');
}
}
I agree with the other responses that it's an issue with your wiring. Try this fiddle as an example: http://jsfiddle.net/reblace/7fVQR/
Declare your outer div like this:
<div ng-app="app" ng-controller="MainController">
And then your controller like this:
var app = angular.module('app', []);
function MainController($scope) { ... }