AngularJS Extending Directive Return - angularjs

I am really new to Angular... I have been trying to google on how to to do this but I think my lack of knowledge keeps me from wording my question correctly thus I am here.
Here is what I am trying to do with my code
ng.module('app.navigation', [
])
.controller('NavigationController', ['$scope', function($scope, $http, $filter){
$scope.message = "Load in the navigation";
}])
.directive('navigation', function() {
return {
templateUrl: 'navigation.view.html',
cssUrl: 'navigation.css',
link: $.NavbarSlide,
};
});
As you can see in my directive return I have put in a cssUrl... this obviously doesn't exist in Angular so what I am trying to do is figure out how to extend Angular with my own 3rd part extension so that I can do something with "cssUrl".

Took a cue from this project https://github.com/marcoslin/angularAMD
ng.module('app.navigation', [
])
.controller('NavigationController', ['$scope', function($scope, $http, $filter){
$scope.message = "Load in the navigation";
}])
.directive('navigation', function() {
return CustomFunction({
templateUrl: 'navigation.view.html',
cssUrl: 'navigation.css',
link: $.NavbarSlide,
});
});
Don't know why I didn't think of this earlier.

Related

Angular Js controller not firing with routes

I am having a problem with AngularJS, where suddenly one of my controllers refuse to execure.
I load it with route, and i know the route is loaded as the html page attached is requested and inserted into the ng-view div i have.
My routes
when('/products/', {
templateUrl: 'app/components/products/products.html',
controller: 'productsController'
}).
when('/products/:productId', {
templateUrl: 'app/components/products/product.html',
controller: 'productController'
}).
I did not see any problems in my controller so i tried replacing all content with just a simple console log, and yet it do still not execute.
angular.module('DietPlanApp').controller('productsController',
['$scope', function ($scope) {
console.log('Get my products!');
}]);
My other controller productController workes just fine.
angular.module('DietPlanApp').controller('productController',
['$scope', '$routeParams', '$location', 'productService', 'userService',
function ($scope, $routeParams, $location, productService, userService) {
productService.getProduct(userService.getUserToken(), $routeParams.productId, function (data) {
if(data.result) {
$scope.product = transferToPortionSize(data.product);
} else {
$location.path("/products/");
}
});
$scope.save = function () {
productService.save(userService.getUserToken(), transferToUnitSize($scope.product));
$location.path("/products/");
};
$scope.delete = function () {
productService.deleteProduct(userService.getUserToken(), $scope.product.id);
$location.path("/products/");
};
}]);
And i have verified that the js files for productsController is loaded correctly in the HTML head, in the same way productController is.
It looks like the result of a namespace collision. You are overwriting productsController in public/app/components/users/authController.js.
It was probably the result of a copy/paste that your forgot to rename. That seems like the most likely culprit.
See the screenshot here.

AngularJS $translate.refresh() not working on load

I'm testing Angular-translate with angular-traslate-partial-loader and it is not populating the page with the default translation on page load.
here is a plunkr of the problem recreated
app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
function($scope, $translate, $translatePartialLoader) {
$translatePartialLoader.addPart('test');
$translate.refresh();
$scope.dotranslate = function() {
$translate.refresh();
};
}
]);
http://plnkr.co/edit/Vts9CW4VoJsXoSdllFsq?p=preview
I added a refresh button to show that the $translate.refresh() works after page load.
What am i missing?
I've never used $translate so I'm not sure exactly what the problem is, but you may be changing a value too late in the digest cycle for the refresh to catch it.
You can use $scope.$evalAsync to fix this. See the angular documentation here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Here is an example of your app.js with the change:
var app = angular.module('plunker', ['pascalprecht.translate']);
app.config(function run($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'translation-{lang}-{part}.json'
});
$translateProvider.preferredLanguage('fr-FR');
});
app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
function($scope, $translate, $translatePartialLoader) {
$translatePartialLoader.addPart('test');
//I wrapped your refresh in the eval async function
$scope.$evalAsync(function() {
$translate.refresh();
});
$scope.dotranslate = function() {
$translate.refresh();
};
}
]);

AngularJS - Consuming REST API with Restangular in a factory

I understand how to use Restangular in a controller, however my thoughts are that Restangular is essentially an ORM on steroids.
The ORM shouldn't have any knowledge of the state of the application. That is the job of the controller.
I also want to re-use queries to the ORM, and as such, I believe that Restangular should be used inside a service.
My problem is that I am a js / angularjs and restangular noob, having only about 2-3 months exp with anything front-end.
My Controllers:
app.controller('AdminSupplierIndexController',
['$scope', '$stateParams', '$state', 'Supplier',
function ($scope, $stateParams, $state, Supplier) {
$state.reload();
Supplier.getAll.then(function (suppliers) {
$scope.suppliers = suppliers;
});
}]);
app.controller('AdminSupplierDetailController',
['$scope', '$stateParams', 'Supplier',
function ($scope, $stateParams, Supplier) {
Supplier.getOne({ supplierId : $stateParams.supplierID}).then(function(supplier) {
$scope.supplier = supplier;
});
}]);
My Factory
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: Restangular.one('supplier', supplierId).get()
};
}]);
My Supplier.getAll method works fine - I can list all the suppliers from the Supplier factory.
My problem is with my Supplier.getOne method.
Question 1: How do I inject the supplierId into the factory? I am getting ReferenceError: supplierId is not defined
Question 2: Am I trying to over-engineer things considering that I would have to create individual methods for C-R-U-D for every single factory when these methods are already provided by Restangular?
I know this is old, but an alternate way would just be to wrap it within a function. This way, you can keep any other logic within the service/method.
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: function(supplierId) {
return Restangular.one('supplier', supplierId).get()
}
};
}]);
Found the solution in https://github.com/mgonto/restangular#decoupled-restangular-service
Essentially, the way I have solved this problem is as follows:
app.js
$stateProvider
...
.state('admin.supplier', {
url : "/supplier",
templateUrl : 'templates/admin/supplier/index.html',
controller: "AdminSupplierIndexController",
resolve: {
suppliers: ['Supplier', function(Supplier) {
return Supplier.getList();
}]
}
})
.state('admin.supplier.detail', {
url : "/:supplierId",
templateUrl : "templates/admin/supplier/detail.html",
controller: "AdminSupplierDetailController",
resolve: {
supplier : ['Supplier', '$stateParams', function(Supplier, $stateParams) {
return Supplier.one($stateParams.supplierId).get();
}]
}
})
...
Supplier.js
app.factory('Supplier', ['Restangular', function(Restangular) {
return Restangular.service('supplier');
}]);
SupplierControllers.js
app.controller('AdminSupplierIndexController', ['$scope', '$stateParams', '$state', 'suppliers',
function ($scope, $stateParams, $state, suppliers) {
$state.reload();
$scope.suppliers = suppliers;
}]);
app.controller('AdminSupplierDetailController', ['$scope', 'supplier',
function ($scope, supplier) {
$scope.supplier = supplier;
}]);

updating ng-model of one angular js controller from another angular js controller

Angular Experts,
I am new to Angular Js and trying to update input in one controller with value from the input in another controller. I am not sure whether it is even possible or not?
I have created js fiddle link just to give an idea.
http://jsfiddle.net/MwK4T/
In this example when you enter a value in controller 2's input, and click 'Set Value it does update biding with <li></li> but does't not update input of the controller 1.
Thanks in advance
I made it working using $broadcast. And it is working like a charm.
I did something like this.
App.controller('Ctrl1', function($rootScope, $scope) {
$rootScope.$broadcast('msgid', msg);
});
App.controller('Ctrl2', function($scope) {
$scope.$on('msgid', function(event, msg) {
console.log(msg);
});
});
Thanks for helping me out.
Best way would be to use the service, we need to avoid the event as much we can, see this
var app= angular.module('testmodule', []);
app.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
app.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
app.service('myservice', function() {
this.xxx = "yyy";
});
Check the working example

Angularjs resolve with controller as string

My style of writing angular controllers is like this (using controller name instead of function)
angular.module('mymodule', [
])
.controller('myController', [
'$scope',
function($scope) {
// Some code here
}
]);
What I need now is when providing i routes I want to define resolve part:
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
resolve: myController.resolve}) // THIS IS THE CRITICAL LINE
Since controller is defined as a name how to accomplish resolve part bellow?
To clarify more in details I want to load some data from server before route is resolved and then use these data in controller.
UPDATE: To be more precise I want each module has its "resolve" function that will be called before root with that controller is executed. Solution in this post (answered by Misko Hevery) does exactly what I want but I don't have controllers as functions but as a names.
The controller definition and resolve parts are to be specified separately on the route definition.
If you define controllers on a module level you need to reference them as string, so:
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
controller: 'myController',
resolve: {
myVar: function(){
//code to be executed before route change goes here
};
});
The above code also shows how to define a set of variables that will be resolved before route changes. When resolved those variables can be injected to a controller so taking the example from the snippet above you would write your controller like so:
.controller('myController', ['$scope', 'myVar', function($scope, myVar) {
// myVar is already resolved and injected here
}
]);
This video might help as well: http://www.youtube.com/watch?v=P6KITGRQujQ
#pkozlowski.opensource 's answer works, but I don't really want to mess up my routing and and controllers, because I always keep it separated (from Yo Generator). Actually, we can also have controller and resolve(r) all as string/name (NOT function).
angular.module('mymodule', [
])
.controller('myController', [
'$scope', 'myModelCombination'
function($scope, myModelCombination) {
// myModelCombination[0] === (resolved) myModel
// myModelCombination[1] === (resolved) myModel2
}
])
.controller('myController2', [
'$scope', 'myModel'
function($scope, myModel) {
// Some code here
}
])
.factory('myModel', [
'$scope',
function($scope) {
// return a promise
}
])
.factory('myModel2', [
'$scope',
function($scope) {
// return a promise
}
])
.factory('myModelCombination', [
'$scope', 'myModel', 'myModel2'
function($scope) {
return $q.all(['myModel', 'myModel2']);
}
]);
Then in your routing file this should be added
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
resolve: ['myModel'] //ALWAYS IN ARRAY)
});
$routeProvider.when('/myModelCombination', {
templateUrl: 'partials/someroute2.html',
resolve: ['myModel'] //ALWAYS IN ARRAY)
});
http://docs.angularjs.org/api/ng.$routeProvider
This would work too
var MyController = myApp.controller('MyController', ['$scope', 'myData', function($scope, myData) {
// Some code here
}]);
MyController.resolve = {
myData: ['$http', '$q', function($http, $q) {
var defer = $q.defer();
$http.get('/foo/bar')
.success(function(data) {
defer.resolve(data);
})
.error(function(error, status) {
defer.reject(error);
});
return defer.promise;
}]
};
#TruongSinh answer worked for me and is way nicer than having additional functions in the router. I tweaked it a little as it was returning the deferred object instead of the actual resolved data.
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
controller: 'SomeController',
resolve: {
myModel: 'myModel'
}
});

Resources