Angular.js Controller can't set properties - html

I'm using a clone of https://github.com/angular/angular-seed to make a simple Angular.js app. I'm trying to put in some properties to the controllers in order to bind them in my HTML but keep getting errors messages that I can't seem to figure out.
My controllers.js file looks like this currently:
'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('MyCtrl1', [function($scope) {
$scope.names = 'bob'
}])
.controller('MyCtrl2', [function() {
}]);
Here is the app.js too if it helps:
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
I've used the default name for the app "myApp" and have also called the ng-view within my HTML. When MyCtrl1 is in use I continually get this error:
TypeError: Cannot set property 'names' of undefined
Is there something syntactically wrong here? I've tried to only modify controllers.js to avoid having issues so there shouldn't be problems elsewhere...

Controllers has a few overloads, you can either simplify your code to this:
angular.module('myApp.controllers', []).
controller('MyCtrl1', function($scope) {
$scope.names = 'bob'
})
.controller('MyCtrl2', function() {
});
Or let Angular know what $scope is like this:
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope', function($scope) {
$scope.names = 'bob'
}])
.controller('MyCtrl2', [function() {
}]);
Reference: http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

Related

to get the parameter from the url in angularjs

I have a page add recommendation and same page for the edit recommendation when I click on the add recommendation the recommendation Id is null in the URL, but when I go the page by clicking the recommendation link it will show that respective Id for the recommendation, in URL it is showing but how to get that Id from the URL to use it.
My code is:
.state('Admin.AddRecommendation',{
url: "/AddRecommendation/:recoId",
templateUrl: "views/AddRecommendation.html",
params: {recoId:null},
})
controller.js:
$scope.addRecommendation = function(){
var id = $routeParams.recoId;
console.log(id);
So where I am doing it wrong.
Thanks
As you are defining recoId in the url, you don't need params: {recoId:null},
.state('Admin.AddRecommendation',{
url: "/AddRecommendation/:recoId",
templateUrl: "views/AddRecommendation.html"
})
You can access the params in the controller by injecting $stateParams
app.controller('MyController', ['$scope', '$state', '$stateParams', function($scope, $state, $stateParams) {
$scope.addRecommendation = function(){
var id = $stateParams.recoId;
console.log(id);
}
}]);
If you are using components, $stateParams is deprecated in favor of $transition$
However, it is not as straightforward to implement that: https://github.com/angular-ui/ui-router/issues/3110#issuecomment-271101827
Basically, you can use it as
.component('foo', {
bindings: { $transition$: '<' },
controller: MyController,
controllerAs: 'vm'
});
app.controller('MyController', ['$scope', '$state', function($scope, $state) {
var vm = this;
$scope.addRecommendation = function(){
var id = vm.$transition$.params().recoId;
console.log(id);
}
}]);
To get the query params from the URL when using ui-router, you can use
In your controller.js:
$state.params
This will give you all the params in the URL. To get specific param:
$state.params[<your-query-param>]
EDIT: In your question, instead of $routeParams, use $state

$injector:unpr Unknown provider on loopback

So, i've searched for an answer to this problem and the solutions presented on the other questions won't work. To be honest i'm already on the testing every possibility.
I have a loopback app with angular and connected to mySQL database.
The explorer from loopback works and i can get and post data to the db.
The problem comes when i try to retrieve it with angularjs on a controller.
what i have is this:
app.js:
angular
.module('app', [
'ui.router',
'lbServices'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('weddings', {
url: '',
templateUrl: 'views/Weddings.html',
controller: 'WeddingsController',
})
.state('Calendar', {
url: '/Calendar',
templateUrl: 'views/Calendar.html',
controller: 'CalendarController',
});
$urlRouterProvider.otherwise('weddings');
}]);
Weddings.js:
angular.module('app').controller('WeddingsController', ['$scope', '$state',
'$http', 'weddings', function($scope, $state, $http, weddings) {
$scope.temp = [];
function getWeddings() {
weddings.find().$promise
.then(function(results) {
$scope.temp = results;
},
function(err) {
$scope.requestsError = err.statusText;
}
);
}
getWeddings();
}]);
That gives me : [$injector:unpr] Unknown provider: weddingsProvider <- weddings <- WeddingsController
if someone can spot something wrong please enlighten me.
Ps: the injections might be too much, im just putting them all out there to see if works :/

AngularJs assign http response object to scope from html

This is the first time I use AngularJs and I would really appreciate some help on this.
I have a json file from which I am retrieving some content that gets displayed on my html template. So far so good.
I need to assign an http response data to the scope from the html.
This is my app
var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller('mainController', ['$scope', '$filter', '$http', '$log', function($scope, $filter, $http, $log) {
$scope.url = "myurl";
$http.get($scope.url)
.success(function(result) {
$scope.page = result;
})
.error(function(data, status) {
$log.info(data);
});
$scope.$watch('productId', function () {
$log.info($scope.productId);
});
}]);
And this is the html
<div class="page" ng-controller="mainController">
<div id="content" class="chapter">
<h1>The Icons Update</h1>
<div ng-init="productId = page[0].acf.spotlight_on"></div>
<p>{{ page[0].acf.spotlight_on_title }}</p>
<p>{{ page[0].acf.spotlight_on_paragraph }}</p>
<img src="{{ page[0].acf.stylist_picture }}" />
</div>
</div>
I need to assign to productId the value of page[0].acf.spotlight_on but need to do it from the html. I just get an undefined value.
Am I right to use ng-init on a div or should I use a different approach? Is there a different way to achieve what I need?
My understanding is that ng-init cannot be used to set scope values after a promise is resolved, which is what is happening when the value is set from $http.get. See angular docs for ngInit https://docs.angularjs.org/api/ng/directive/ngInit
In your question you say you need to set the value of productId in the html, however this appears impossible where it is returned by a promise.
The alternative is very simple to do in the controller by simply using the following:
var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller('mainController',
['$scope', '$filter', '$http', '$log',
function($scope, $filter, $http, $log) {
$scope.page = {};
$scope.productId = '';
$scope.url = "myurl";
$http.get($scope.url)
.success(function(result) {
$scope.page = result;
// set the value of productId from the result
$scope.productId = result[0].acf.spotlight_on;
})
.error(function(data, status) {
$log.info(data);
});
}]);
If you use ng-init, then it creates a scope variable which is only limited to the element(and its children) where you have defined it. In other words, it won't be available in your controller which is why you get 'undefined'.
To tackle this, you can use $parent, which will create the scope variable in your controller:
ng-init="$parent.productId = page[0].acf.spotlight_on"

Read local file in AngularJS

I used to work with RequireJS and Backbone and used requirejs/text and requirejs-plugins to load local json files I normally use for configuration.
How does one achieve the same with AngularJS?
Everyone seems to suggest to use $http, but is this the only way?
Do I really need to make 20 calls if I have 20 configuration files?
Maybe something like ng-constant is the "preferred" way?
This is what I did. But it uses $http though so I'm hoping someone has a better solution.
app.js:
var myModule = angular.module('myApp', []);
myModule.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'html/home.html',
controller: 'MainCtrl as ctrl',
resolve: {
initializeData: function($q, $timeout, myService) {
return myService.promiseToHaveData();
}
}
});
});
myService.js:
var myModule = angular.module('myApp');
myModule.service('myService', function($http, $q) {
var _this = this;
this.promiseToHaveData = function() {
var defer = $q.defer();
$http.get('someFile.json')
.success(function(data) {
angular.extend(_this, data);
defer.resolve();
})
.error(function() {
defer.reject('could not find someFile.json');
});
return defer.promise;
}
});
Then I can inject myService anywhere and it will have all the fields from the json file.
I guess alternatively you could just make your .json files .js files, have them expose a global variable, and reference them in your index.html
Can you use jQuery's getJSON function?
E.g something like:
$.getJSON("config-1.json", function( data ) {
// do whatever you want
});
Here's an AngularJs service that uses the FileReader API:
http://odetocode.com/blogs/scott/archive/2013/07/03/building-a-filereader-service-for-angularjs-the-service.aspx

How to use a angularjs route to call a javascript function

I'm trying to use the routing of angularjs to call a javascript function if a certain url is used.
The following code is not providing the expected result:
var app = angular.module('myApp', []);
app.config(function($routeProvider) {
$routeProvider.when('/link1', {
controller: 'PageController'
})
.when('/link2', {
controller: 'PageController'
})
.otherwise({
controller: 'PageController'
});
});
app.controller('PageController', function($scope, $routeParams) {
alert('1');
});
The alert(1); is not called if one of these URLs are requested...
Maybe someone knows how to solve this ?
Controller is not called until you specify template or templateUrl option in $routeProvider configuration. If there is no template needed, you could specify one-space char (but not empty string). Like so
$routeProvider.when('/link1', {
controller: 'PageController',
template: ' '
})
There is no way to associate the routing with a specific action in the controller. The routing in the AngularJS is not like the routing in other web frameworks to route to specific action of request. Instead, the routing in the AngularJS is primarily relating to handle the page flow and the controller defines the scope of the page.
However, if you put the alert in the controller like that, it should be triggered when the page is loaded. You need to check whether the URL you used is correct or not. To test, you can simply put $location.url('/link1') in your code.
If your controller is being used on a particular route, then you can call that function inside the controller. It will get executed once the route changes and your controller is called.
In this http://plnkr.co/edit/qUZ5Q7nKCRAS8dFvjRIg when you click on link1 it displays alert.
I can't quite catch why your code doesn't work as expected, but I created a similar app setup and it works:
var app = angular.module('myApp',[]).
config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/', {
controller: 'PageController',
template: '<br><br>this is page #/<br> {{data}}',
}).
when('/link1', {
controller: 'SpecificPageController',
template: '<br><br>this is page #/link1<br> {{data}}'
}).
when('/link2', {
controller: 'PageController',
template: '<br><br>this is page #/link2<br> {{data}}'
}).
otherwise({redirectTo:'/'});
}]).
controller('PageController', function($scope, $routeParams) {
$scope.data = 'hello world';
}).
controller('SpecificPageController', function($scope, $routeParams) {
$scope.data = 'hello specific';
alert(1);
});
Whenever SpecificPageController is assigned to a route, and that route opened, the alert function gets executed.