How to connect my controller in my directive for inserting data and adding bootstrap select in angular.js? |
Try adding controller in your directive itself like ths;
angular.module('myApp.directives', [])
.directive('selectpicker', function() {
return {
restrict: 'C',
controller: function($scope){
$scope.cities = [
{value:'1',name:'Angeles'},
{value:'2',name:'Angono'},
{value:'3',name:'Antipolo'},
{value:'4',name:'Apalit'},
{value:'5',name:'Arayat'},
{value:'6',name:'Bacolod'},
{value:'7',name:'Bacoor'}
];
},
link: function(scope,el,attr,cntr) {
$(el).selectpicker();
}
}
});
|
Angular using another directive's controller? |
http://plnkr.co/edit/vq7vvz
There were two problems with your plunkr:
In order for a directive to require the controller of another directive,
the two directives have to be on the same element, or if you use the ^
notation, the required directive can be on a parent element.
<div dir-one dir-two></div>
Also, in the second directive you called your parameter "scope" but then
tried to use it as "$scope".
link: function(scope, element, attrs, dirOneCtrl) {
scope.options = dirOneCtrl.getOptions();
alert(scope.options);
}
|
Function within angular directive that I can call from the controller |
Firstly in your HTML change myDir to my-dir. In your case you dont need to
give an id to your div:
<div my-dir>My dir</div>
<button ng-click="clickme()">click me</button>
Now expose dirFunction to the scope. This would make it possible for your
controller to access this function:
app.directive("myDir", function(){
return function(scope){
scope.dirFunction = function(){
alert("hello world");
}
}
});
And from within your controller just call it as $scope.dirFunction():
app.controller("Control", function($scope){
$scope.clickme = function(){
$scope.dirFunction();
}
});
NOTE: You should not do DOM manipulation inside your controller:
angular.element('#myDir').dirFunction(); in controller is a bad way to co
|
Angular access controller scope from nested directive |
Use
<div ng-transclude></div>
instead of
<ng-transclude></ng-transclude>
in the template of modal directive.
|
How to catch an event in controller which is thrown by an directive in Angular? |
In you Plunker, second controller (SecondController) is registered, but it
is never actually initialized. So that's why your listener never logs the
event.
It's not clear how, where and when you are using using your second
controller, but if you initialize it with either ng-view (through routes)
or ng-controller, than its listener will observe the event.
PLUNKER
|
Applying Angular directive ngCloak to a single Controller |
Try this:
Add a style in your stylesheet:
.ng-cloak { display:none; }
Then use ng-cloak as a class instead of an attribute:
<div id="stats" ng-controller="Statistiche" class="ng-cloak">
e.g. http://plnkr.co/edit/xWPW2i?p=preview
should work now.
Remember, you can use directives as classes as well, not just attributes
and elements.
Edit, just tested this, and you dont have to put it into a class. So just
add the .ng-cloak style into your stylesheet.
|
Angular - receiving info from controller inside directive |
Without knowing your exact use-case, my approach would be to define a new
scope property, e.g. play : "=" (to set it to stop when the video ends),
and $observe attrs.play or $scope.$watch "play" it. In your template you
bind it to a $scope variable that is triggered by the controller.
<video-item play="videoControls.play"></video-item>
Here's a plunker where you use two-way binding, note how you don't have to
do anything:
http://plnkr.co/edit/3OI801KcvYVoySDvcm8i?p=preview
If you want to allow expressions, you have to observe the attribute to get
the interpolated value:
http://plnkr.co/edit/gi6FSPPlN599CtDjKBOb?p=preview
|
Unit-test a angular controller function in a directive |
In your case you could test the elements controller by accessing
controllers functions from the compiled elements scope.
The easiest way to access the scope of the element is by calling the
#scope() function on the compiled angular element.
it ('should have a function X on scope', inject(function($rootScope,
$compile) {
var element = $compile('<div
test-directive></div>')($rootScope);
expect(element.scope().myFunction).toEqual(jasmine.any(Function));
});
Heres a simple example of the following technique used in a jsFiddle.
|
Adding directive makes controller undefined in angular js code |
You are defining the demo module twice. By passing a second argument to the
angular.module method, you create a new module. Don't pass the second
argument to return a reference to an existing module:
// Create a module
angular.module("demo", []).controller('DemoController', function ($scope) {
// ...
});
// Get reference to module
angular.module("demo").directive('myDatepicker', function ($parse) {
// ^ Only one argument
});
Note that the controller method returns the module to allow chaining, and
the module method also obviously returns the module, so you also have two
other options:
Chaining:
angular.module("demo", []).controller('DemoController', function ($scope) {
// ...
}).directive('myDatepicker', function ($parse) {
// ...
});
Storing reference t
|
AngularJS service/controller not updating angular-leaflet-directive map |
I had a similar issue. In my case, I have a div tied to a controller
wrapping the leaflet tag element:
<div ng-controller="MapCtrl">
<leaflet id="map" class="map" maxBounds="maxBounds"
defaults="defaults" center="center"></leaflet>
</div>
As you can imagine, the values for "maxBounds", "defaults", and "center"
were in the parent $scope, not the $scope of the directive. To mitigate
this, I had to modify the angular-leaflet-directive code to look up the
scope stack for these variables:
var mapScope = $scope;
if (mapScope.defaults === null || typeof mapScope.defaults === "undefined")
{
mapScope = mapScope.$parent;
}
if (mapScope.defaults === null || typeof mapScope.defaults === "undefined")
{
throw new Error("Cannot find map defaults - have they been in
|
Angular Directive throws $digest already in progress when trying to call controller method |
Your scope.$apply is not needed there. The link function is called and the
template is built with the scope, so you are trying to apply scope changes
for template that is being built
http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
One way to solve it is:
app.directive('summary', function(){
return {
restrict: 'A',
scope : {
summary : '='
},
templateUrl: 'summary.html',
link: function(scope, elem, attrs){
console.log('directive: call to load pie1');
scope.summary();
}
}
});
app.controller('SummaryController', function($scope){
console.log('controller glued');
$scope.loadPie1 = function() {
console.log('controller: will load pie1');
};
});
<div summary="loadPie1"></div>
You can pass the actual function
|
Update data in angular directive |
you should ba able to use $watch, but you can also use the isolate scope
attribute and then pass your controlle $scope variable directly to your
directive
I tweaked a little your code and I added some console.log in order to see
what happens, you can see it here http://jsfiddle.net/DotDotDot/uC2dP/14/
I added a button on top, to force the modification of the positions, in
order to see the repercussion in the directive, and in the directive I
added a console.log() with the positions called on scroll. Also your
directive now have an isolated scope, with the resultsSections binded to
the parameter given in the HTML
return {
scope:{resultsSections:"=sections"},
link:function(scope, element, attrs) {
var height = $(window).height(),
section = 0;
$(window).bind("scro
|
Angular directive data binding not working properly |
Update:
Here is a very rudimentary implementaion using jquery datepicker -
http://plnkr.co/edit/4JZIWo6mJqg59F5o7xdh?p=preview
angular
.module("demo", [])
.directive("test", function() {
return {
restrict: 'A',
scope: {
time: "="
},
link: function(scope, element, attrs) {
console.log("scope.time:" + scope.time);
$(element).datepicker();
$(element).datepicker("setDate", scope.time);
}
};
})
.controller("demoCtl", function($scope){
$scope.parentTime = new Date();
});
Have a look at angular-ui calendar module. If you don't want to use it,
you can look at their code to help you.
Also, the way you set up your scope looks strange. I think you want to
bind you directive's time property, to a property managed by the dire
|
angular - controllers .then function called after directive so no data avail async call |
Try using the success and error methods of the returned $http object if
you're just trying to set a value. These methods are specific to the
objects returned by $http.
$http.get('data/data.json')
.success(function(data, status, headers, config){
$scope.result = data;
})
.error(function(data, status, headers, config){
console.log(data);
)};
Any errors that you're getting could also be helpful.
Also you probably don't want to couple your directive so tightly with your
controller by referencing $scope.result. You may want to just pass in the
data to render as an attribute, in which case egghead.io has some great
tutorials on the subject (directive isolate scope).
|
Directive model binding doesn't work under angular ui bootstap tabs directive |
The AngularUI boostrap directive creates a child scope, so a quick fix is
to use the following inside your "Second" tab:
<my-directive ng-model="$parent.ranges"></my-directive>
|
Angular js passing a variable from a parent directive to a child directive |
First, the correct syntax to "require" the parent controller is:
require:"^supNavDirective"
Second, you must add returnNavTree method to the controller instance itself
(instead of $scope) to access it from the child directive, like this:
...
controller: function ($scope, $element) {
this.returnNavTree = function(){
return $scope.navtree
}
},
...
|
Getting user data from server in angular controller without exposing data |
Directive
myModule.factory('User', function($http) {
return {
getUser: function () {
// deferred object
var deferred = $q.defer();
$http.get('/fetch_user.json') {
.success(function (data, status) {
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject("An error occured while trying to get
users");
});
}
return deferred.promise;
}
}
}
Contoller:
myModule.controller('MyController', ['$scope', 'User', function($scope,
User) {
User.getUser().then(function (data) {
$scope.user = data;
});
}]);
I'm assuming /fetch_user.json is the url, if not just replace it.
Upd
|
Is it possible to call functions from parent directive controller, when subsidiary directive has isolated scope |
directives can share controllers via the require property, that you
correctly specified. this is what Angular's docs on directives say about
accessing the directive's controller (emphasis added):
"require - Require another directive and inject its controller as the
fourth argument to the linking function. The require takes a string name
(or array of strings) of the directive(s) to pass in. If an array is used,
the injected argument will be an array in corresponding order. If no such
directive can be found, or if the directive does not have a controller,
then an error is raised"
IMHO, when applied to your case, this means that the link function where
the controller is injected is the one in your child directive, not in the
parent
|
Rendering AngularJS directives from array of directive names in a parent directive or controller |
So the second attempt would have worked had I used $compile on the
prepended directives like so:
.directive('parentDirective', function($compile)
....
element.prepend($compile('<div ' + scope.directives[i] +
'"></div>')(scope));
|
In Angularjs can a controller nested inside a directive set the ng-model of the directive? |
http://jsfiddle.net/jSEba/
This is one way to satisfy your need by using event emission.
i.e. letting directive to $broadcast event into its child scope,
so that transcluded child scope can catch via $on to react to the
button click.
angular.module('myApp', [])
.directive('fooDirective', function(){
var template = '<div><div ng-transclude></div>
<button ng-click="someFunc()">I want to update ng-model in the
directive, which in turn will update myController
$scope.viewModel.foo</button></div>';
return {
transclude: true,
template: template,
link: function(scope, elem, attrs) {
scope.someFunc = function() {
scope.$broadcast('buttonclick', { valname:
attrs.fooDirective });
};
|
Angularjs control flow from directive to controller back to directive |
In my solution I'm allowing a service to have access to the markers that
are on the map and another service which communicates to the backend for
content.
The service that accesses the marker allows me to add a directive for the
popup and bind it to a marker. The popup directive could have additional
information that is filled out by the retrieved data.
The content getting service works by using a promise, which is resolved
with the data when the backend returns. I just used a $timeout, but you
will be using $http.
me.GetData = function() {
var def = $q.defer();
$timeout(function() {
def.resolve('<span> wooo! </span>');
}, 2000);
return def.promise;
};
The popup service binds to the marker (with some default elements if
needed) and waits for the con
|
Angular JS / Data Binding / Controller |
Communicating between controllers, please check the below fiddle.
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
|
Passing data from one controller to other Angular |
What about creating some kind of a message bus in your app?
First, create a MessageBus service:
module.factory("MessageBus", function($rootScope) {
return {
broadcast : function(event, data) {
$rootScope.$broadcast(event, data);
}
};
});
Then, inject it to the originator controller:
function OriginatorController($scope, MessageBus) {
$scope.funct = function(e) {
// get data
MessageBus.broadcast("data", data);
};
};
And subscribe to events anywhere you want:
$scope.$on("data", function(arguments) {
console.log(arguments);
});
You can even use $rootScope directly via DI and call $broadcast on it in
your controllers, but creating a service is more expressive.
EDIT: Here is a pen for you.
|
angular.js: using a directive to insert another directive as an attribute |
After the compilation, AngularJS only calls $compile for all of the child
elements. The element itself is not automatically recompiled, so adding a
directive at this stage will not have effect. In your case, I think you can
change it from a compile function to a link function (so you get a scope
argument), and call $compile(element)(scope) yourself.
See this Fiddle where I have a directive that adds style="color: red", and
another directive that "dynamically" adds that directive. It doesn't work,
unless I call $compile afterwards.
HTH!
|
angular ng-animate directive with ng-show directive |
You need to be running AngularJS version 1.1.4 or newer, with 1.1.5 being
the latest right now. You also need to use a different set of CSS rules
— they've changed since the first release.
Updated jsbin
Modify your HTML to point to 1.1.5:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
And change your CSS rules to use .show-animation for setup and
.show-animation.show-animation.active for the active animation:
.show-animation {
background-color:red;
-webkit-transition:all linear 0.5s;
-moz-transition:all linear 0.5s;
-ms-transition:all linear 0.5s;
-o-transition:all linear 0.5s;
transition:all linear 0.5s;
opacity: 0;
}
.show-animation.show-animation-active {
background: blue;
opacity: 1;
}
Also please n
|
Angular.js - How to pass data from controller to view |
After going through the comments, i understood you are using one controller
for two views.
If you want to set values to $scope.registeredDate and $scope.filedDate,
You have to declare those objects globally using root-scope(Not
recommended) or
use Angular values.
I recommended to use two different controllers.
|
Can't extract data from controller for angular-chosen |
If the screenshot shows the console.log of allgroups, then your ng-options
should be ng-options="pergroup.name for pergroup in allgroups.result", OR
allgroups = $myResource.result.
|
how to post data From angular js to zend controller? |
Change your main.js like this;
function LoginCtrl($scope, $http) {
$scope.login = {email: "", password: ""};
$scope.login = $.param($scope.login);
$scope.submit = function(){
$http({
method: 'POST',
url: '/login',
data: $scope.login,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(response) {
window.location.href = "/login";
}).
error(function(response) {
$scope.codeStatus = response || "Request failed";
});
}
In your php file access your email and password like;
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
and send these credentials to your zend controller. Hope it helps.
|
Feeding the data through an angular factory to a controller |
Your problem is not the controller but the way you define the service, with
a factory: Angularjs - Declaring factory with a single object with a nested
array - getting ReferenceError: .... is not defined
You should probably be doing something like:
app.factory('GetOverSpeedWorstData', function ($scope,$http) {
var r;
$http.get('http://localhost:5155/overspeedworst/OverSpeedworst').success(function
(data, status) {
stuff, like r = data
}).error("error message");
error stuff
});
return {service methods here};
otherwise your factory is not factoring anything. it has to return
something.
|
Pass data to angular's nested controller |
You can use "resolve" -
var dialog = $dialog.dialog({
resolve: {route: function(){return "route"}}
});
and later you can inject the "route" value inside of your controller
.controller("SomeCtrl",function(route){
})
|
trying to use angular-ui-bootstrap radiobutton directive with ng-repeat in an angular project |
Try this:
<button type="button" class="btn" data-ng-repeat="(key, value) in items"
ng-model="radioModel" btn-radio="key">{{key}}
({{value.length}})</button>
Notice btn-radio="key", just drop {{}} and ''
|
Angular app resolve, not controller, for async pre-loaded data |
Here's what I did. I'm not a huge fan of this solution, but it's the best
I've been able to come up with so far.
First of all, you can have multiple resolves in each route, like so:
resolve: {
UserAccount: app.resolves('UserAccount'),
Posts: app.resolves('Posts')
}
Since you can't inject application services into the config block, I
created a big old object in another file that contains shortcuts to my
services:
app.resolves = (function(){
// Resolves allow us to use `deferred`s to only
// load our template after the data it requires
// has been provided by the server.
var resolve = {};
resolve.UserAccount =
['Users', function (Users) {
return Users.fetchActive();
}];
resolve.Posts =
['Posts', function(Posts) {
return Posts.getAllPosts();
}];
//
|
Angular JS POST request not sending JSON data |
If you are serializing your data object, it will not be a proper json
object. Take what you have, and just wrap the data object in a
JSON.stringify().
$http({
url: '/user_to_itsr',
method: "POST",
data: JSON.stringify({application:app, from:d1, to:d2}),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
$scope.users = data.users; // assign $scope.persons here as promise is
resolved here
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
|
Angular.js - Data from AJAX request as a ng-repeat collection |
You need to collect data from DOM when an update from the server arrives.
Save whatever data is relevant (it could be only the input values) and
don't forget to include the identifier for the data object, such as
data._id. All of this should be saved in a temporary object such as
$scope.oldInvoices.
Then after collecting it from DOM, re-update the DOM with the new data (the
way you are doing right now) $scope.invoices = data.
Now, use underscore.js _.findWhere to locate if your data._id is present in
the new data update, and if so - re-assign (you can use Angular.extend
here) the data-value that you saved to the relevant invoice.
|
Ajax request to controller to get data for DropDownList in asp.net? |
You could return it as a JSON result:
public ActionResult GetTraumaType(string passedString)
{
if (passedString == "Industrial")
{
return Json(some_value, JsonRequestBehavior.AllowGet);
}
else
{
return Json(some_other_value, JsonRequestBehavior.AllowGet);
}
}
and then:
$.ajax({
type: "POST",
url: '@Url.Action("Action", "Controller")',
data: { passedString: "Industrial"},
success: function(data) {
// here you could rebind the ddl:
var ddl = $('#TraumaCode'); // verify the id of your ddl
ddl.empty();
$.each(result, function() {
ddl.append(
$('<option/>', {
value: this.value,
html: this.te
|
How can I POST data to a WebAPI controller from Angular's $http service? |
$http.post('/api/MyResource/MyPostAction', data);
Remove the JSON.stringify and post the data as is.
You don't need to specify json header either as it is the default for post.
On the server:
Remove Xml from webapi if you're only using json
//WebApiConfig.js
var appXmlType =
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t =>
t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
|
AngularJS Directive with no Template and Sharing the updates from parent scope |
You can remove the $watch in the directive if you adopt the following
approach.
You should use the object interpolation html.push("{{" + attrs['zippy'] +
"}}"); instead of the serialized plain text string if you want the model to
be interpolated and updated.
app.directive('zippy', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var html = [];
html.push('<hr/><div class="clearfix" id="vote-icons"
ng-click="primitiveTest(' + attrs['zippy'] + ');" >Update Name
</div> - <div class="clearfix" id="vote-icons"
ng-click="objectTest(' + attrs['zippy'] + ');">UpdateObject');
html.push('</div>');
html.push("{{" + attrs['zippy'] + "}}");
el
|
Angular JS: sending form field data in a PUT request (like POST does) |
Because your $scope.realmen is a resource instance, instead of using
RealMen.update, you can just call $scope.realmen.$update() (note that there
is a "$"). The instance action method will take care of sending the data
for you.
|
Angular Directive to Directive call |
It sounds like you are looking for a directive controller. You can use the
require: parameter of a directive to pull in another directive's
controller. It looks like this:
app.directive('foo', function() {
return {
restrict: 'A',
controller: function() {
this.qux = function() {
console.log("I'm from foo!");
};
},
link: function(scope, element, attrs) {
}
};
});
app.directive('bar', function() {
return {
restrict: 'A',
require: '^foo',
link: function(scope, element, attrs, foo) {
foo.qux();
}
};
});
From the angular docs, here are the symbols you can use with require and
what they do.
(no prefix) - Locate the required controller on the current element.
? - Attempt to locate the requir
|
how can I build up model data in Angular JS service or controller with multiple calls? |
I would handle this in the service. Something along the lines of:
.factory('Device', function($resource){
var device = $resource('/prodCatVisualiser/ajax/product/:id');
for (var rel in device.relationships) {
rel.data = $resource(/prodCatVisualiser/ajax/product/:id).get({id:
rel.relId});
}
return device;
});
(warning - off the cuff code, probably contains an error somewhere, I
haven't had coffee yet...consider as pseudocode)
Now what your controller receives will go through three states:
A promise of the main product data
A fulfilled promise for the main product data, containing pending promises
for each of the relationship products.
A completely fulfilled promise with data for all of the products needing to
be displayed.
Far from breaking MVC, this support
|