I am having trouble with something very simple like inject a basic service into a controller and despite reading documentation and other SO question i really don't see the mistake i'm making.
Here's my simplified code:
angular.module ('travelApp', ['ui.bootstrap', 'ngRoute'])
//CONTROLLERS
.controller('searchController', ['$scope','myParams', function ($scope,ngRoute,myParams){
$scope.place = myParams.place;
$scope.$watch('place', function(){
myParams.place = $scope.place;
});
$scope.bind = function(){
console.log(myParams.getPlace);
};
}])
//SERVICES
.service('myParams', function(){
this.place = 'start';
});
//MY HTML
<div class="container" ng-app="travelApp">
<div class="jumbotron" id="searchPage" ng-controller="place">
<div>
<h3>Start Here</h3>
<input type="text" class="form-control" id="searchBar" ng-model="place">
<a type="button" class="btn btn-default" ng-click="bind()">bind data</a>
</div>
</div>
I have tried a number of things in the past few hours but keep getting the
"TypeError: Cannot set property 'place' of undefined"
It seems the service is just no available inside the controller, i don't know if it has something to do with routing but i doubt so.
Can someone please point me in the right direction?
Here is a Plunker
Your dependencies must match if you use array syntax. Remove ngRoute from the controller's arguments.
.controller('searchController', ['$scope','myParams', function ($scope, myParams){
Related
I'm new in AngularJS, and can't do the simple task. I hope that you will help me.
My goal is to display the $scope property "server" from controller to text input in the view when it's loaded:
My controller:
(function () {
'use strict';
angular
.module('app')
.controller('HomeController', homeController);
homeController.$inject = ['authService', 'httpService'];
function homeController(authService, $scope) {
var vm = this;
vm.auth = authService;
$scope.server = SERVER_HOST_NAME;
console.log ($scope.server);
}
})();
var SERVER_HOST_NAME = "anysite.com"; is global.
And I want, that the text input in the view is display that for loading.
My view is
<h4 ng-if="vm.auth.isAuthenticated()">
You are logged in!
</h4>
<h4 ng-if="!vm.auth.isAuthenticated()">
You are not logged in! Please <a ng-click="vm.auth.login()">Log In</a> to continue.
</h4>
<div class="container">
<label>Team city server:</label>
<input ng-model="server" type="text" />
<button ng-click="getBuilds()">Extract</button>
</div>
I use ng-model to bind my property to textinput, but have no idea why it is not working. I guess this is simple task. Thank you.
why you are mixing up both $scope and vm ? use vm and controller as syntax on HTML as follows,
vm.server = SERVER_HOST_NAME;
and the HTML would be,
<input ng-model="vm.server" type="text" />
So this is how my index.html is structured.
<html ng-app='information'>
<body ng-controller="FirstController as first>
<div ng-controller="SecondController as second>
<div id="information">
<myOwnDirective ng-controller="ThirdController as thirdCtrl"></myOwnDirective>
</div>
This is my custom directive.
(function() {
var app = angular.module('information', ['ui.bootstrap']);
app.directive('myOwnDirective', function(){
return {
restrict: 'E',
templateUrl: 'my-own-directive.html',
};
});
This is a custom directive template. my-own-directive.html
<uib-accordion tag ng-repeat="info in first">
<form ng-submit="thirdCtrl.updateInformation()">
<div class="form-group">
<label for="someprop">Property</label> <input type="text" name="someprop"
class="form-control" ng-model="info.propValue"
ng-readonly="info.propValue">
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">Click</button>
</form>
This is my script file: myScript.js
(function() {
angular.module('information').controller('ThirdController', [ '$scope', function($scope) {
console.log("In third controller"); // This prints
this.updateInformation = function() {
console.log("Inside updateInformation");
console.log("Inside scope is: "+ $scope) // It is undefined
};
}]);
})();
What I want to get is get value of info.propValue from the scope but I cant seem to get it. It always shows up as undefined. I have a very long form whose contents I want to read but I cant seem to get the values. Once I have them I will bemaking an Ajax call using $http. Also, if I try to invoke function updateInformation() by doing $scope.updateInformation(), it doesnt invoke, but it does get called if I do this.updateInformation(). Why ?? What am I missing or what am I doing wrong? Any help is appreciated. Have been stuck on it for quite a while. Thank you.
I have the following Form which I am including in the main app through ng-view
Form Snippet
<form action = "#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" type="text" ng-model="userComment" placeholder="New Discussion Topic" rows="5"></textarea>
</div>
</div>
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn" type="button" id="submitComment" ng-click="vm.addComment()">Submit comment</button>
</div>
</div>
</form>
Upon clicking the submit button, the controller function will be called. In the controller function, I am not able to access the variable $scope.userComment
Controller Snippet
(function () {
'use strict';
angular
.module('app')
.controller('DiscussionBoardController', DiscussionBoardController);
DiscussionBoardController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function DiscussionBoardController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
function addComment() {
$.getJSON(
"http://localhost/DBoardPage/server/discussion-board/postComment.php", // The server URL
{ userName: $scope.currentUser , userComment:$scope.userComment , commentID:0 }, // Data you want to pass to the server.
$scope.addCommentResponse // The function to call on completion.
);
};
/*End - Discussion Board related Functions*/
}
})();
Though I know that a child scope will be created when we use ng-include, ng-view and ng-repeat, I am not getting an example to explain the usage.
Please let me know how I can get around this preoblem
Are you sure it isn't $scope.currentUser that doesn't exist? You are using a variable that isn't declared.
Try adding:
$scope.currentUser = "";
$scope.userComment = "";
Since you are using AngularJS it might be a better idea creating your function the Angular way.
$scope.addComment = function(){....
If it still doesn't work show more of your setup.
I have two DIVs, each one is a self-contained user control or partial view, if I want one team to work on dog div, the other team work on fox div. can each team have their own angular module, controller, view, etc ? If yes, can you show me a code snippet?
another question: if I want to these two DIVs loosely coupled, what is the best angular way to let them communicate ?
<body ng-app>
<div id="dog">
<input type="text" ng-model="name"/> {{name}}
</div>
<div id="fox">
</div>
</body>
Thank you!
For other new ng developer's reference, this is the final code, if you have better solution, please feel free to improve it.
<body ng-app="airborneApp">
<div id="dog" ng-controller="dogController">
<input type="text" ng-model="name" /> {{name}}
</div>
<div id="fox" ng-controller="foxController">
<input type="text" ng-model="name" /> {{name}}
</div>
<script>
angular.module('airborneApp', ["dogCompany", "foxCompany"]);
angular.module('dogCompany', []).
controller('dogController', ['$scope', function ($scope) {
$scope.name = 'hello dog';
}]);
angular.module('foxCompany', []).
controller('foxController', ['$scope', function ($scope) {
$scope.name = "hello fox";
}]);
</script>
</body>
You can make as many modules as you can, you just have to reference all of them as a dependency in you main App module definition (and load them in correct order)
app
angular.module('myApp', ['firstModule', 'secondModule'])
modules
angular.module('firstModule', []) // empty array as a second parameter creates new module instead of using existing one
.controller(...)
.directive(...)
angular.module('secondModule', [])
.controller(...)
.directive(...)
For communication between different modules, the simplest way is to inject $rootScope into all controllers.
But preferred way is to create a service in main app module, which will be injected into both modules
angular.module('myApp')
.factory('SharedData', function() {
var a = {},
b = {};
return {
a: a,
b: b
}
})
and then use it
angular.module('firstModule')
.controller('something', function($scope, SharedData) {
SharedData.a.data = 'new data';
})
angular.module('secondModule')
.controller('something else', function(SharedData) {
console.log(SharedData.a.data); //will output 'new data'
})
each div can have a separate controller using:
<div ng-controller="firstCtrl"></div>
<div ng-controller="secondCtrl"></div>
for the other part of your question see:
What's the correct way to communicate between controllers in AngularJS?
I am trying to use div with ng-click for routing:
ng-click="go('/item/{{item.id}}').
I can call $parent.go or even go when using ParentCtrl. But ParentCtrl_2 does not work at all. I tried to look for some answers, but can't figure it out. What am I missing?
app.controller('ParentCtrl', function($scope) {
$scope.go = function(path) {
console.log(path);
}
}
);
app.controller('ParentCtrl_2', ['$scope', '$location',
function($scope, $location) {
$scope.go = function(path) {
$location.path(path);
}
}
]);
app.controller('ChildCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
...
}
]);
There are number of unanswered questions here but, like what is the structure of your html ng-controller structure.
Also the call sytax in html is wrong for
ng-click="go('/item/{{item.id}}')
It should be
ng-click="go('/item/'+ item.id)"
Said that depending on where the ng-click is declared it would have access to parent methods. If you can access a method using $parent then you can access the method directly due to prototypal inheritance.
If structure is like
<div ng-controller='ParentCtrl'>
<div ng-controller='ParentCtrl_2'>
<div ng-controller='ChildCtrl'>
<!-- ng-click somewhere here -->
</div>
</div>
</div>
Then you access the ParentCtrl_2 method go whenever you call.
If it is
<div ng-controller='ParentCtrl'>
<div ng-controller='ParentCtrl_2'>
</div>
<div ng-controller='ChildCtrl'>
<!-- ng-click somewhere here -->
</div>
</div>
Then you have access to ParentCtrl method go method only.