Controller outside ui-view - angularjs

I want to use a unique controller inside and outside ui-view.
Using ng-inspector I see <div ui-view> has another instance of myController, not sure why.
<div class="container" ng-controller="myController">
::{{_path}}
<a ng-click="action()">action</a>
<div ui-view class="view"></div>
</div>
app.controller("myController",function ($scope) {
$scope.action = function(){
$scope._path= "changed";
}
});
The result of this issue is if I click on <button ng-click="action()">action</button> I see the changes in _path, if the same button is inside ui-view, _path doesn't changes. How can I make this work?

When you define your state you can specify the controller you want to use inside your view as follows:
$stateProvider.state('myState', {
url: '/my-state',
templateUrl: '/templates/my-state.html',
controller: 'myController'
});
Hope this helps.

Related

ng-model not working in ui-router nested view

I have the following code structure
index.html
<body ng-app="jobPortalApp" ng-controller="mainController">
<div ui-view></div>
</body>
then following is my homepage.html template
<div id=header>
</div>
<div ui-view>
<input type="text" ng-model="test">Test</input>
<input type="submit" ng-click="signup()">
</div>
<footer>
</footer>
my angular module file is as follows
var jobPortalApp = angular.module('jobPortalApp',['ui.router']);
jobPortalApp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home',
{
url:'/',
templateUrl: './templates/homepage.html',
controller: 'controllerHome'
})
}).controller('mainController', function(){});
following is my home controller
jobPortalApp.controller('controllerHome',function($scope, $http) {
$scope.test="";
$scope.signup = function() {
console.log($scope.test);
}
});
Required:
I want the changed value of test in my controllerHome after the user clicks on signup
Problem:
console.log outputs blank and if I remove $scope.test="";then outputs undefined. I want the changed value of test in my controller.
You usually shouldn't bind directly to $scope due to issues with prototypal inheritance. When trying to read a value from a child scope, if the value doesn't exist you end up reading from the parent scope. But as soon as you write, you write to the child scope. Does it work if you bind to an object instead?
$scope.data = {
test: ""
};
<input type="text" ng-model="data.test">Test</input>
As an alternative, you may also want to look at the controllerAs option for your route:
controllerAs: "ctrl"
Then in your controller:
this.test = "";
And in your template:
<input type="text" ng-model="ctrl.test">Test</input>

Passing data from html div tag to controller in AngularJS

I have a div in my html. Inside the div I am invoking a controller. I need to pass some data from div to the controller. I don't have any other html element in div like input fields/buttons etc.
<div ng-controller="writeLoadTimeController">
<!--adding this controller to send the page load time to server-->
$scope.loadTime=$window.performance.timing.domContentLoadedEventEnd-$window.performance.timing.navigationStart;
</div>
How do I pass the value of the loadTime field to the controller.
you can try:
<div id="loadTime" ng-controller="writeLoadTimeController" ng-load="someFunction()">
</div>
and controller:
$scope.someFunction = function(){
$scope.loadTime=$window.performance.timing.domContentLoadedEventEnd-$window.performance.timing.navigationStart;
}
1: You can add onload event to the div and call a function which will calculate the loadTime for you. It should be like this.
you html:
<div id="loadTime" ng-controller="writeLoadTimeController">
</div>
and the controller:
app.controller("writeLoadTimeController", function($scope){
$scope.loadTime ="";
document.getElementById("loadTime").addEventListener('onload', onloadHandler);
function onloadHandler(){
$scope.loadTime=$window.performance.timing.domContentLoadedEventEnd-$window.performance.timing.navigationStart;
}
});
Then you can use {{loadTime}} in the html.
2: You can avoid adding onload listener and do the following:
you html:
<div id="loadTime" ng-controller="writeLoadTimeController">
</div>
and the controller:
app.controller("writeLoadTimeController", function($scope){
$scope.loadTime ="";
$scope.loadTimeCalculator = function(){
$scope.loadTime=$window.performance.timing.domContentLoadedEventEnd-$window.performance.timing.navigationStart;
}
$scope.loadTimeCalculator();
});
It will call loadTimeCalculator() function when the writeLoadTimeController is called.
Hope this will help you:)

Angular: Why Won't Model Update Outside Of View In Same Controller?

I have found a number of posts talking about models/views not updating, but I still can't figure this out. I'm new to Angular, btw so I suspect this is noob issue.
I have the below Angular app.
When the text input test_var is edited, the edited value isn't updated in the sidebar, but it is in the view. Why and how do I fix it?
This works when I don't use views and routes.
I've tried a sidebar controller, but no difference. I've tried $rootScope, which partially worked (it broke other functionality), but I'd prefer not to use a global scope.
Thanks for taking a look.
HTML
<body>
<div ng-app="rxApp" ng-controller="WizardCtrl">
<div class="ng-view">
</div>
<div class="sidebar">
<span ng-bind="test_var"></span>
</div>
</div>
</body>
View (One.html)
<input ng-model="test_var" />
<span ng-bind="test_var"></span>
Controller
rxApp.controller( 'WizardCtrl', function ( $scope, $http, $routeParams, $location, FileUploader ) {
$scope.test_var = 'please work!';
)};
Routes
rxApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/one', {
templateUrl: 'templates/one.html',
controller: 'WizardCtrl'
}).
when('/two', {
templateUrl: 'templates/two.html',
controller: 'WizardCtrl'
}).
otherwise({
redirectTo: '/one'
});
}
]);
Controllers are disposed when transmuting routes.
As for Best Practice you should create a Service to handle that data. You should not use controllers to carry data between views. In your case, the problem is Controllers are disposed when transmuting routes.
See the angular docs on how to use controllers correctly. http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller
The problem is the making of model variables.
You have to have a dot in model. Make your model point to an object.
So in your controller do like this -
rxApp.controller('WizardCtrl',function($scope, $http, $routeParams,$location, FileUploader){
$scope.test ={
var : 'please work!'
};
)};
View (One.html)
<input ng-model="test.var" />
<span ng-bind="test.var"></span>
HTML
<body>
<div ng-app="rxApp" ng-controller="WizardCtrl">
<div class="ng-view">
</div>
<div class="sidebar">
<span ng-bind="test.var"></span>
</div>
</div>
</body>
To read more about scope go through this UnderStanding Scopes

Param at ui-sref not passed

I have my ui-sref code here.
<div class="container">
<div ng-repeat="vendor in Items"
id="scrollArea">
<img src='{{vendor.img}}'
style='width:100%;'
ui-sref='vendordetail({vendorId:1})'/>
</div>
</div>
And my $stateProvider
.state('vendordetail',{
views:{
url:'/:vendorId',
'mycontainer':{
templateUrl:'vendordetail',
controller:function($scope, $stateParams) {
console.log('vendordetail controller');
console.log($stateParams);
}
}
}
});
The templateUrl "vendordetail" is displayed on the targeted ui-view "mycontainer" successfully. "vendor detail controller" string is logged as well. But the $stateParams is an empty object {}. What did I actually missed out to pass the param vendorId to my state controller?
I hope I am not missing out any context. Thanks in advance.

nest ng-view inside a form

given the controller
function ctl($scope, $http) {
$scope.postForm = function() {
console.log("submitting form")
}
}
and the view
<form name="pform" ng-show="!error.Show">
<div ng-view></div>
<button type='button' value='Save' ng-click="postForm()" />
</form>
The controller method postForm doesn't get called, however, if i move the form tag into the view the method is called. Is there a reason that this doesn't work as I expect it to? Is there another way to accomplish the goal of sharing the form controls across different views?
Update
my module and routeProvider are configured like this:
angular.module("profilemodule", [])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/info", { templateUrl: '/partials/profile/info.html', controller: ProfileController })
.when("/user", { templateUrl: '/partials/profile/user.html', controller: ProfileController })
.when("/introduction", { templateUrl: '/partials/profile/editor.html', controller: ProfileController })
.otherwise({ redirectTo: '/info' });
}]).run(function ($rootScope, $location) {
$rootScope.location = $location;
})
and the page includes some nav elements which are set based on the location service like so:
<div class="row">
<div class="offset2 span10">
<ul class="nav nav-pills">
<li ng-class="{active: location.$$path.substring(0, '/info'.length) == '/info'}"><a href="#/info" >Information</a></li>
<li ng-class="{active: location.$$path.substring(0, '/user'.length) == '/user'}"><a href="#/user" >User</a></li>
<li ng-class="{active: location.$$path.substring(0, '/intro'.length) == '/intro'}"><a href="#/intro" >Introduction</a></li>
</ul>
</div>
</div>
<form name="pform" method="POST" ng-show="!error.Show">
<div ng-view></div>
<button type='button' value='Save' ng-click="postForm()" />
</form>
the ng-class statements works perfectly, is it because I've set the location property of $scope in the module's run method?
thanks,
jason
ng-view with routing creates a new scope with the controller, and you can't reach a child scope. Your submit action lies in the parent scope and the form data lies in the child scope (created by ng-view).
If you want to use common form controls, you can use ng-include, this directive gets template it and renders that in the current scope.
Move your form controls to a new template, then include them in all of your forms.
API reference:
http://docs.angularjs.org/api/ng.directive:ngInclude

Resources