mardi 5 mai 2015

AngularJS - Remove iOS scrolling and window dragging

I've seen a lot of similar questions to this but none seem to provide me with a solution that is working for me. So I'm using an AngularJS app and it's been made to feel very much like a native app on your phone, so it shouldn't really use any of Apple's bouncing scroll. If I drag the window I get something very similar to this:

http://ift.tt/1GZZgmg

It's not great when you're trying to create a native-feeling web app, so how would I go about removing this?

Angularized Bootstrap Menu Not Collapsing after Link Click

I have a Angularized bootstrap menu that works if it is loaded in a view, but not when in the index.html. I need it in the index.html before the views (data-ng-view) since I have content between the menu and views. When placed before my views in the index.html page, if I click on a link, I am able to go that link... but the menu stays open instead of closing after going to a link. I am using AngularUI and have injected 'ui.bootstrap' into the App (that is how it works when loaded in a view). The controllers for my views are tied to the page they relate to.

Example:

when('/home', { templateUrl: './views/home.html', controller: 'homeCtrl' }).

Here is my navigation:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-ng-init="isCollapsed = true" data-ng-click="isCollapsed = !isCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="/"><h1 id="pfch1">My Title</h1></a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" data-ng-class="{collapse: isCollapsed}">
        <ul class="nav navbar-nav">
            <li><a href="/home">Home</a></li>
            <li class="dropdown" data-ng-class="{ open : dd1 }" data-ng-init="dd1 = false" data-ng-click="dd1 = !dd1">
                <a class="dropdown-toggle" role="button" aria-expanded="false" href="#">Categories <span class="caret"></span></a>
                <ul class="dropdown-menu" role="menu">
                    <li><a href="/categories/1/cat1">cat1</a></li>
                    <li><a href="/categories/2/cat2">cat2</a></li>
                    <li><a href="/categories/5/cat3">cat3</a></li>
                    <li><a href="/categories/4/cat4">cat4</a></li>
                    <li><a href="/categories/6/cat5">cat5</a></li>
                    <li><a href="/categories/3/cat6">cat6</a></li>
                </ul>
            </li>
            <li><a href="/add-article">Add Article Link</a></li>
        </ul>
        <form class="navbar-form navbar-right">
            <div class="form-group">
                <div data-ng-controller="userInfo">
                    <div data-ng-controller="loginCtrl" data-ng-hide="loggedin">
                        <input class="btn btn-default" type="submit" value="Login" data-ng-click="login()" />
                    </div>
                    <div data-ng-controller="loginCtrl" data-ng-show="loggedin">
                        <input class="btn btn-default" type="submit" value="Signout" data-ng-click="logout()" />
                    </div>
                </div>
            </div>
        </form>
    </div>
</nav>

Here is the relevant section of index.html (please note that the menu above is included via an ng-include. I have tried it without the ng-include but it still doesn't collapse):

<body>
<!-- Container start -->
<div class="container">
    <!-- Top Menu -->
    <div data-ng-include="'templates/topmenu.html'"></div>
            <div data-ng-view></div>
           <hr>
    <footer>
        <p>&copy; My Site 2015</p>
    </footer>
</div>
<!-- Container end -->
</body>

Django Rest Framwork and Angular

I am very new Django Rest Framework and Angular Js. What I wandering here is the best way to work with these two.

  1. Django Rest and Angular js together (Most of tutorials showed me this)
  2. Django Rest as backend and Angular js in frontend as 2 different projects

I am very confused, though I feel the 2nd approach is better. But still not sure. Can please anyone help me in this with pros and cons of both the approaches

Angular JS works in main layout(view) but not in child view of laravel 4.2

I'm trying to use Angular JS with Laravel 4.2. I've changed the blade's default {{}} into [[]], it works perfectly, now the problem is that when I puts Angular JS code in main layout (view) it works but when I put Angular JS code in a child view(actually child view extends the main layout and section is yielded using @section('contents') ...Angular JS code... @stop) it doesn't work at all, browser can't render the Angular JS exprerssion and shows it as it is in code editor! Here is my "main layout.blade.php" and "child.blade.php":

"main.layout.blade.php"

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Customer Management</title>

    <!-- Bootstrap -->
    [[ HTML::style('css/bootstrap.min.css') ]]
    [[ HTML::style('css/custom.css') ]]

    [[--angular js files--]]
    [[HTML::script('/js/angular/angular.min.js')]]
    [[HTML::script('/js/controllers.js')]]

    [[--jquery bootsrtap js files--]]
    [[ HTML::script('js/respond.js') ]]
    [[ HTML::script('js/jquery-1.11.2.min.js') ]]
    [[ HTML::script('js/bootstrap.min.js') ]]

</head>

<body>

    @include('layouts.main-menu')

    <div class="container" id="container">
        <div ng-app=""><!-- This Angular JS works fine -->
            <p>Name : <input type="text" ng-model="name"></p>
            <h1>Hello {{name}}</h1>
        </div>

        @yield('content')
    </div>

    @include('layouts.footer')


    <script>
        $("nav ul li").on("click", function() {
            $("nav ul li").removeClass("active");
            $(this).addClass("active");
        });
    </script>
</body>
</html>

Child.blade.php

@extends('layouts.main')
<!doctype html ng-app="myApp">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

</head>
<body>

    @section('content')
        <div ng-app=""><!-- This Angular JS doesn't work fine -->
            <p>Name : <input type="text" ng-model="name1"></p>
            <h1>Hello {{name1}} </h1>
        </div>
    @stop
</body>
</html>

You can see clearly that same Angular Code snippet is used in both files but in "layout.main.blade.php" it works and in "child.blade.php" it doesn't work as it is in between @section('content') ... @stop I can't get understand why this is and how to solve it!!!!!!

how to add directive attribute to element in link function?

As we known, the angular have performance if there are more than 2000 records in the page, because only some of the records need add some behavior , so I would prefer to dynamically add attribute to element according model value in link function, as there will be less watches.

So I use $compile to recompile the element like below:

mainApp.directive("popoverSetting", function ($compile) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            if (scope.item.isTrue) {
                element.attrs("ns-popover-trigger", "mouseenter");
                element.attrs("ns-popover-timeout", "0.01");

                $compile(element)(scope);
            }
        }
    }
})

Because there are about 1000 records, so the speed is very slow, is there some other way to add attribute and compile quickly? although there only 5 records need to add these attribute, it still increase about twofold time than before.

How to store data for my complex web app, similar to JS Fiddle

I'm designing a web app and I'd like to make sure that my data model will work and can grow. If anyone knows any resources or standards I should follow, I'd appreciate that too. Basically, it's a complex note application with the following pieces:

I have things called chapters, the user can only see one chapter at a time. A chapter consists of 2 parts : pages and comments.

The left half of the window houses the pages (there can be multiple pages). For sake of simplicity, a page is just a string of text.

The right half will contain the comments. In other words, when a user selects a certain sentence in a page, a comment will pop up.

I'd like to have as many of these chapters as necessary, and I haven't come up with a navigational structure but I suspect I'll need to be able to group chapters together.

Right now, how I was thinking about it was having an array for each chapter so it looks like this:

[
    {
        "page": "asd",
        "comments": another array
    },
    {
        "page": "random string, will include html elements"
        "comments": another array
    }
]

I'm using angular JS and using ng-repeat to loop through this array and display all the pages. Then depending on which comment the user clicks on, the selected comment will show up on the right side.

So I don't have a unique id for each chapter- is there a standard way? I also think I need some kind of id for comments, since there can be many comments per page. I was looking into guid's but I've never used them before.

I was thinking of having this comments array:

"comments": [ {"id": "guid", "comment":"asfasfd"}, {"id": "guid", "comment":"asfasfd"}]

I also wanted to assign a guid for each chapter. For testing, I was going to keep all the chapters in one json file.

What is generally done for stuff like this? For example, how does JS Fiddle store it's data? I assume there are chunks for the html, the JS and the CSS, along with metadata, but I'm not sure how their data model actually looks like.

How to navigate to a cordova/ionic page in android fragment with all styles and scripts loaded?

I am developing a hybrid application with angularJS and ionic. All the screens are html. After login user will pick some actions in the left panel and action screen will be displayed in the right panel. It is working fine in iOS. Due to some deign issues we decided to go with native for action panel and action screens in android. But still we have a html5 screen for a action menu item for android (simple HTML5 form). My problem with android is:

  • User logs in (HTML5 login screen)
  • Action screen displayed with left panel and right panel (native android)
  • User picks an action in the left, right panel displays the action screen. (native)
  • User picks a specify action xx in the left panel. Now show the HTML5 action screen inthe right panel.

I am using Android fragment and Cordova web view to load the HTML5 action screen for the specif action xx. But the screen is loaded without styles and other angular/ionic stuff. (using cordovawebview.loadUrl())

Because user is already logged in, app should show the action screen with all styles and JS applied. How do I do that ?

writing an $httpProvider for a long-polling comet app

TL;DR: Are there examples of Angular with long-polling integration out there? (Examples, specifically Comet examples would be nice!)

Our current app uses Angular and Comet. The client sends out long-polling requests that stay open until the server has data to return. When the server returns data, the data payload might have several messages for different 'channels'.

The out-of the box Comet JS code we have uses jQuery's $.get(), $.post() methods to make the long-polling requests.

Angular is built on a light version of jQuery and adds lots of (Angular-related) magic compared to $.get()/$.post() via Angular's $http object.

I've been told the Angular's $http object and the promises it returns are not compatible with message-based front-ends, but I'm not convinced

Is it true they are incompatible?

I was thinking a different $httpProvider that is Comet aware could be written, that would provide an $http object, that based on URL could determine if it should behave in normal ajax mode or long-poll mode.

The idea here is that typically each Comet channel has a message listener and the listener has a callback it invokes passing in the message.

To me this seems like a promise in disguise. Generally, the idea would be to create a promise for each channel. When the $http object is dealing with a long-poll request, when the server responds with data it would know how to parse the payload into messages for each channel, and then resolve each channel (which is now a promise in Angular world). Resolving each channel would have the effect of calling the channels/promises then() function.

Doesn't this achieve message-based behavior with listeners and callbacks? Are these just the same things, but with different names?

I'm considering toying with the approach and possibly prototyping it. But before I do, does this even make sense?

How these promises would resolve in Angular HTML templates I'm still uncertain about.

Are there already examples of Angular with long-polling integration out there?

I couldn't find any.

Get error : [$injector:unpr] Unknown provider: socketProvider <- socket <- LogCtrl

I am new to AngularJs and nodejs and I have a simple chat app with angular as client and socketio as server side. I got an error when loading angular page

Error: [$injector:unpr] Unknown provider: socketProvider <- socket <- LogCtrl

My client side

    <script src="http://ift.tt/1xHFqJ2"></script>
<script src="http://ift.tt/1ELJDLe"></script>
<script src="http://localhost:1337/socket.io/socket.io.js"></script>

<script type="application/javascript">
     socket = io.connect('http://localhost:1337/');
     angular.module('Log',['ngRoute'])

             .controller('LogCtrl',['$scope','socket','$location', function($scope,socket,$location){

                 console.log('ok baby !!');

                 $scope.addUser = function(){
                     socket.emit('init',$scope.user);
                     $location.path("/view/index.html");
                 };

             }]);
 </script>

<body  ng-app = "Log" >
<div class=" main"  ng-controller = "LogCtrl" style = "width: 300px; ">
<fieldset>
     <form  ng-submit = "addUser()">
         <h2 >Hello!!</h2>
         <input ng-model = "user" required  style = "width: 200px; " placeholder = "Nhập tên của bạn" >
         <input type = "submit" value = "OK">
    </form>
</fieldset>
</div>

Please help me what wrong with my client

Angular JS Can't interpolate: $selectMultiple.getPlaceholder()

So, i have this implementation of multi select ui on a form with other fields:

This is the view:

<div class="form-group">
<label for="components" class="col-sm-2 control-label">Components</label>
<div class="col-sm-10">
  <ui-select multiple ng-model="service.components" theme="bootstrap">
        <ui-select-match placeholder="Select a component">{{ $item.name }}</ui-select-match>
            <ui-select-choices repeat="component in components">
                <small ng-bind-html="component.name"></small>
        </ui-select-choices>
    </ui-select>
</div>

And in the backend i get the data on this way:

http.get('config/init_data.json').then(function(res) {
    service.components = res.data.components;
});

When i perform the submit function, everything works fine, get the data in the multiselect, show me the selected ones and creates the object perfectly. The problem is when i want to perform the same action for second time... in that case i get the error:

Error: [$interpolate:interr] Can't interpolate: {{$selectMultiple.getPlaceholder()}} TypeError: Cannot read property 'length' of undefined

ui-select error “Can't interpolate: {{$select.getPlaceholder()}}” have the same problem but the solution don't work for me.

Any ideas? Thank you some much for your help.

Include HTML/PHP in JS variable

I have the following JS code:

{var c;a.stores=[{name:"Nijiya Market",price:"$$",sales:292,rating:4},{name:"Eat On Monday Truck",price:"$",sales:119,rating:4.3}]

I call on these variables to produce an html table. What I want to do is use html within the JS variable to produce an image instead of text. So for example:

{var c;a.stores=[{name:"<img src='url'>",price:"$$",sales:292,rating:4},{name:"<img src='url'>",price:"$",sales:119,rating:4.3}]

Can anyone suggest how I do this and if the same method would work with php.

Don't know if it matters, but I am using AngularJS.

Thanks.

How to share user settings in 2 browsers

We have a scenario like this:

angular.module('xxx').service('PersistenceService', [ '$rootScope', '$window', function ($rootScope, $window) {
    'use strict';

    function makeKey(key) {
        return $rootScope.session.userName + '_' + $rootScope.session.tenantId + '_' + key;
    }

    this.get = function (key) {
        return $window.localStorage.getItem(makeKey(key));
    };

    this.set = function (key, value) {
        $window.localStorage.setItem(makeKey(key), value);
    };

    this.remove = function (key) {
        $window.localStorage.removeItem(makeKey(key));
    };
}
]);

Currently in our web app, we store the user settings in the Local Storage(js localStorage), the shortage of the local storage is we can't share the settings cross 2 sessions(may be 2 browsers is easy to understand).

Now we want to save the user settings to the server side so user can share his application settings via different browsers.

Here is the question: In our project, the API to interact with local storage is a synchronize design, 1.)if we keep the old interface, and do the sync server logic in each interfaces, the performance is very low. 2.)if we use promise to sync with server, lots of codes need to be changed.

I think neither of above 2 method is acceptable. Currently what i can think of is: Fetch the user settings on app initializing and copy the settings to localStorage, so we can use the old interfaces to without change any code out side of the persistence service. We also need to sync server logic in method(Set, Remove)

Does anyone have any better ideas? Thanks in advance!

What is best practise for user authentication across subdomains between an AngularJS UI and a Lithium API?

I have setup a lithium REST API with an AngularJS UI as two separate projects. For the setup of the UI I originally followed this tutorial before going down a slightly different approach. The UI has a session service that effectively syncs session data between itself and a PHP session which is started on the first request to the API. I have been building the apps and testing them locally on a vagrant box and they have been working fine with one and other but when it came to pushing them to the staging environment each call to the API would create a new session key and would not authenticate further than the single login request.

I have read some articles on cross domain security issues but from the sounds of it CORS is secure and may be what I'm looking for. I have had a little play setting the headers on my apache virtual host config in the staging environment to try to make the sessions persist with the UI ajax calls but without any luck.

So I guess my question is: is there a way to make this type of setup work across domains api.domain.com and ui.domain.com and is it secure?

The API currently only outs the standard 401 authentication status code and the UI uses an auth interceptor service on the $httpProvider to detect the status. The interceptor then calls $rootScope.$broadcast AUTH_EVENTS.unauthorized to broadcast that the app has lost authentication with the API and calls $state.go "login" to prompt the user to login.

I plan to add the 403 forbidden status down the line once I have implemented some form of ACL.

Lithium session bootstrap

use lithium\storage\Session;

$name = basename(LITHIUM_APP_PATH);
Session::config([
    'default' => ['adapter' => 'Php', 'session.name' => $name]
]);

use lithium\security\Auth;

Auth::config([
    'default' => [
        'adapter' => 'Form',
        'model' => 'Users',
        'fields' => ['email', 'password']
    ]
]);

use lithium\action\Dispatcher;
use lithium\action\Response;

Dispatcher::applyFilter('_callable', function($self, $params, $chain) {
    $controller = $chain->next($self, $params, $chain);
    $request = isset($params['request']) ? $params['request'] : null;
    $action = $params['params']['action'];
    $publicActions = isset($controller->publicActions) ? (array) $controller->publicActions : [];

    if (!in_array($action, $publicActions) && !Auth::check('default', $request)) {
        return function() use ($request) {
            return new Response(['status' => 401]);
        };
    }

    return $controller;
});

Bulk of the AngularJS

app = angular.module "App", ["ui.router"]

app.constant "AUTH_EVENTS",
    authenticated: "auth-authenticated"
    unauthorized: "auth-unauthorized"
    forbidden: "auth-forbidden"

app.config [
    "$httpProvider"
    "$stateProvider"
    "$urlRouterProvider"
    ($httpProvider, $stateProvider, $urlRouterProvider) ->

        $httpProvider.interceptors.push [
            "$injector",
            ($injector) ->
                $injector.get "AuthInterceptorFactory"
        ]

        $urlRouterProvider
        .otherwise "/home"

        $stateProvider
        .state "login",
            controller: "AuthController"
            controllerAs: "Auth"
            url: "/login"
            templateUrl: "./partials/login.html"
        .state "home",
            controller: "HomeController"
            controllerAs: "Home"
            url: "/home"
            templateUrl: "./partials/home.html"

]

app.run [
    "$rootScope"
    "$state"
    "AUTH_EVENTS"
    "AuthFactory"
    ($rootScope, $state, AUTH_EVENTS, AuthFactory) ->

        $rootScope.$on AUTH_EVENTS.authenticated, ->
            $state.go "home"

        $rootScope.$on AUTH_EVENTS.unauthorized, ->
            $state.go "login"

        $rootScope.$on "$stateChangeStart", (event, toState) ->
            if toState.name isnt "login" and not do AuthFactory.check
                do event.preventDefault
                $rootScope.$broadcast AUTH_EVENTS.unauthorized

]

app.factory "AuthInterceptorFactory", [
    "$rootScope"
    "$q"
    "AUTH_EVENTS"
    ($rootScope, $q, AUTH_EVENTS) ->
        responseError: (response) ->
            statuses =
                401: AUTH_EVENTS.unauthorized
                403: AUTH_EVENTS.forbidden
            $rootScope.$broadcast statuses[response.status], response
            $q.reject response
]

app.factory "SessionFactory", [
    "$http"
    "$q"
    ($http, $q) ->

        get: ->
            deferred = do $q.defer
            $http
            .get "api/session.json"
            .success (data) ->
                deferred.resolve data
            .error ->
                deferred.reject "Unable to get session."
            deferred.promise

        create: (key, value) ->
            deferred = do $q.defer
            data =
                key: key
                value: value
            $http
            .post "api/session.json", data
            .success (data) ->
                if data.success is undefined
                    deferred.reject "Unable to create session."
                else
                    do deferred.resolve
            .error ->
                deferred.reject "Unable to create session."
            deferred.promise

        remove: (key) ->
            deferred = do $q.defer
            $http
            .delete "api/session.json?key=" + key
            .success (data) ->
                if data.success is undefined
                    deferred.reject "Unable to delete session."
                else
                    do deferred.resolve
            .error ->
                deferred.reject "Unable to delete session."
            deferred.promise

]

class SessionService

    key: null

    data: {}

    constructor: (@$q, @$rootScope, @AUTH_EVENTS, @SessionFactory) ->
        do @get

    get: ->
        deferred = do @$q.defer
        get = do @SessionFactory.get
        get.then(
            (data) =>
                @key = data.key
                @data = data.data
                if @data.user
                    @$rootScope.$broadcast @AUTH_EVENTS.authenticated
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    write: (key, value) ->
        deferred = do @$q.defer
        create = @SessionFactory.create key, value
        create.then(
            =>
                @data[key] = value
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    read: (key) ->
        if @data[key] is undefined then null else @data[key]

    remove: (key) ->
        deferred = do @$q.defer
        remove = @SessionFactory.remove key
        remove.then(
            =>
                delete @data[key]
                do deferred.resolve
            (reason) =>
                deferred.reject reason
        )
        deferred.promise

    destroy: ->
        @key = null
        @data = {}

app.service "SessionService", [
    "$q"
    "$rootScope"
    "AUTH_EVENTS"
    "SessionFactory"
    SessionService
]

app.factory "AuthFactory", [
    "$http"
    "$q"
    "$rootScope"
    "AUTH_EVENTS"
    "SessionService"
    ($http, $q, $rootScope, AUTH_EVENTS, SessionService) ->

        login: (credentials) ->
            deferred = do $q.defer
            $http
            .post "api/users/login.json", credentials
            .success (data) ->
                if data.user
                    writeSession = SessionService.write "user", data.user
                    writeSession.then ->
                        $rootScope.$broadcast AUTH_EVENTS.authenticated
                        do deferred.resolve
                else
                    deferred.reject "Unable to login."
            .error ->
                deferred.reject "Unable to login."
            deferred.promise

        logout: ->
            deferred = do $q.defer
            $http
            .get "api/users/logout.json"
            .success (data) ->
                if data.success
                    do SessionService.destroy
                    $rootScope.$broadcast AUTH_EVENTS.unauthorized
                    do deferred.resolve
                else
                    deferred.reject "Unable to logout."
            .error ->
                deferred.reject "Unable to logout."
            deferred.promise

        check: ->
            not not SessionService.read "user"

]

Execute a function on ANY state reload/page refresh (UI-router)?

I need to call a function when ANY state is reloaded. Essentially, if the user refreshes the browser, I need to call something. Is there any way to do this without modifying EVERY state with $state.reload()?

I CAN put a controller on index.html which contains all the views/states if this would help.

Changing super-navbar-buttons titles

New to AngularJS in Supersonic/Steroids/Appgyver

I know this is not working, but are there some variants that would work:

<super-navbar-button side="left">
    {{ titleButtonLeft  }}
</super-navbar-button>
<super-navbar-button side="right">
    {{ titleButtonRight }}
</super-navbar-button>

while

$scope.titleButtonLeft = "Left"
$scope.titleButtonRight = "Right"

Alternatively, change the title by code on super-navbar-buttons without removing and adding them.

Can't seem to access the buttons specifically with, for example:

supersonic.ui.navigationBar.buttons.right[0]

or

supersonic.ui.views.current.navigationBar.buttons.left[0]

even though they should reside somewhere therein, according to:

http://ift.tt/1EWjBGT

Any suggestions?

AngularJS double ng-repeat

I'm working on accordion group and have two ng-repeat. Outer one repeats weeks from current week to a specific date. Inner repeats working hours sever days in each week.

function expand(week.id) is to call database and prepare data for variable "hour".

My problem is that when I click on one accordion-heading to show data in week#1, the rest of all other weeks(accordions) also show the same data, which makes this process very slow.

How could I just render the trs under the heading where I clicked? E.g My scenario is when I click on heading of week#1, only trs under week#1 are rendered.

Could anyone help me with this?

  <accordion-group   ng-repeat="week in weeks">
        <accordion-heading >
            <span ng-click="expand(week.id)">{{week.firstday}}--{{week.lastday}}</span>
        </accordion-heading>
        <table class="table table-striped">
            <thead>
            <tr>
                <th>Task</th>
                <th>Sun</th>
                <th>Mon</th>
                <th>Tue</th>
                <th>Wed</th>
                <th>Thu</th>
                <th>Fri</th>
                <th>Sat</th>
                <th>Total</th>
            </tr>
            </thead>
            <tbody id={{week.id}}>
            <tr ng-repeat="hr in hour">

                <td> <select class="form-control input-sm" ng-disabled="false"><option value="hr.task_name">{{hr.task_name}}</option></select></td>
                <td><input type="number" min="0" ng-model="hr.sun" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.mon" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.tue" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.wed" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.thu" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.fri" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><input type="number" min="0" ng-model="hr.sat" class="form-control"  placeholder="Hours" ng-disabled="true"></td>
                <td><span class="form-control">{{hr.sun+hr.mon+hr.tue+hr.wed+hr.thu+hr.fri+hr.sat}}</span></td>
            </tr>
            </tbody>
        </table>
         </accordion-group>

AngularJS, Browserify and module loading

Alright, I have no clue. I searched the internet for like 3 days now and couldn't find any example on how to use Browserify in combination with AngularJS and Gulp. Yes there are examples but they all show that simple 'hello world' app structure nobody will use in the end anyway. They all write their little controllers inside the main app.js file. No modular setup. And the modular setups I found, well .. they include all the files by hand in the index.html file.. sigh (sorry for my tone).

What i try to achieve is to autoload all my application files but it just doesn't work. What do i need to do to include my controller files? Isn't that what browserify is for? Why isn't it working?

The first answer will probably be: you need to require() the files. But how? I tried require('myApp.mainController'); as well as require('src/features/main/main-controller.js') with the result of:

Error: No Module found.

If someone can point me in the right direction, please help me! :). Thanks in advance! The necessary info is below the line.


Project structure

|project
|-builds
| |-development
| |-production
|-src
| |-components
| |-features
| | |-main
| | | |-main-ctrl.js
| | | |-main.html
| | |-dashboard
| | | |-dashboard-ctrl.js
| | | |-dashboard.html
| |-app.js
| |-app.scss
| |-index.html

app.js

require('angular');
require('angular-ui-router');

var app = angular.module('myApp', [
  'ui.router',
  'myApp.mainController'
]).config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  $stateProvider
    .state('main', {
      url: '/',
      templateUrl: 'src/features/main/main.html',
      controller: 'mainController'
    })
    .state('dashboard', {
      url: '/dashboard',
      templateUrl: 'src/features/dashboard/dashboard.html',
      controller: 'dashboardController'
    })
}]);

main-ctrl.js

angular.module('myApp.mainController', [])

  .controller('mainController', ['$scope', 'Main', function($scope, Main) {
    $scope.message = Main.message;
}]);

gulpfile.js

gulp.task('js', function() {
  return browserify({
    entries: 'src/app.js',
    debug: true
  })
    .bundle()
    .pipe(gulp.dest('builds/development'))
    .pipe(connect.reload());

});

How to set class to first item in ng-repeat that has been sorted with orderBy?

I have a list of items, which comes in unsorted, I use orderBy to sort by name alphanumerically.

<li class="ticker-li"
    ng-repeat="ticker in tickers | orderBy:'ticker'"
    ng-class="{'selected':ticker.selected}">

Now in my controller this is how I'm currently setting the first items selected class:

var vs = $scope;
vs.tickers = data;
vs.tickers[0].selected = true;

^ This worked perfectly until I needed to add the orderBy so that items appear by alpha order:

enter image description here

I found this answer here, however it locks the first item to always have the class.

Modifying my code a bit, I was able to have other buttons gain that class on click, however the $first item still stayed with the class.

ng-class="{'selected':$first || ticker.selected}"

enter image description here

How should the code either in the markup or controller need to be updated to fix this issue?

Angular module won't display data

Pretty new to angular so forgive me. I am trying to work with chart.js to display some data I am pulling off of a webservice. I have tested that the $http.get() works by putting the data in a table, plus console logs. The issue I am having is when using these chart js templates the data is always in the html, obviously I wanted to put it in a js file. So I included the ng-app and ng-controller but it still wont work:

<html>

  <head>
    <script data-require="jquery@*" data-semver="2.1.3" src="http://ift.tt/16ygW8q"></script>
    <script data-require="angular.js@*" data-semver="2.0.0-alpha.20" src="http://ift.tt/1DRvsRh"></script>
    <script data-require="chart.js@*" data-semver="0.2.0" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myapp" ng-controller="MainCtrl">
    <div id="canvas-holder">
            <canvas id="chart-area" width="500" height="500"></canvas>
        </div>
        <button id="randomizeData">Randomize Data</button>

  </body>

</html>

There isn't much to the html, which Is why I am wondering why it isn't working?

I made a plunker with everything and it worked up until I added the angular.module().controller() stuff. Any ideas? Thanks.

cordovaSQLite retrieving data slowly using ionic framework

I am making an application using the ionic framework and I am using sqlite to store a list of about 150 rows. Each row has two attributes, ID and Name.

Now I am retrieving this data using a database factory which runs a query.

It works, however when I test it on an my Galaxy Tab 3 the list takes about 5-10 seconds to load and once it it loaded the list it super laggy scrolling through the list items.

Here's my controller

.controller('ActionSearchCtrl', function($scope, ActionSearchDataService, DBA, $cordovaSQLite){

    var tablet = true;
    var query = "select action FROM actions;";


    $scope.items = []; 

    $scope.runSQL = function(){
        DBA.query(query).then(function(result){
            $scope.items = DBA.getAll(result);
        });
    }; 

    if(tablet){$scope.runSQL()};

Here's my Database Factory

.factory('DBA', function($cordovaSQLite, $q, $ionicPlatform) {
  var self = this;

  // Handle query's and potential errors
 self.query = function (query, parameters) {
    parameters = parameters || [];
    var q = $q.defer();

    $ionicPlatform.ready(function () {
      $cordovaSQLite.execute(herbsDatabase, query, parameters)
      .then(function (result) {
        q.resolve(result);
      }, function (error) {
        console.warn('I found an error');
        console.warn(error);
        alert(error.message);
        q.reject(error);
      });
    });
    return q.promise;
  }

  // Proces a result set
  self.getAll = function(result) {
    var output = [];
    for (var i = 0; i < result.rows.length; i++) {
      output.push(result.rows.item(i));
    }
    return output;
  }


  // Proces a single result
  self.getById = function(result) {
    var output = null;
    output = angular.copy(result.rows.item(0));
    return output;
  }
  return self;
})

So the query returns about 150 entries which I need all on one page (I've looked into infinite scrolling and pagination but my client wants all the items on one page so this is not an option. From what I've read, 150 entries shouldn't be too slow in terms of watchers as I am using ng-repeat for the list items to display. If anyone has a way I can display this many items using the cordovaSQLite plugin to make the list function quicker let me know! at the moment the list is pretty much unusable, I've tried it on other devices too and it has the same result.

I've also tried creating about 200 dummy objects in the controller (without making a call to the db to get data) and the performance is fine. That's why I am thinking it's an SQLite performance issue. This is my first post on here so apologies if I am not clear enough.

Angularjs Push does not work

I want to push an element in my html interface using angularjs, this element appears only when I refresh the url.

this is a portion of my html code :

   <nav class="navbar-default navbar-side" role="navigation"  ng-         controller="createController">
         <li ng-repeat="project in projects" id="proj" >
                <a  style="background: #AFAFAF"> <i ng-click="remove(project.id)" class="fa fa-fw fa-trash-o"></i>
                   {{project.name}}
                    <ul>

this is the push in my controllers:

        $scope.projects.push({"idProject": idp, "name": namep, 'path':  directory});

How to send multiple checkbox value using Angular post method to PHP?

I'm new to Angular and I don't know to send multiple checkbox value to PHP (Server-side).

Code: http://ift.tt/1EPc8YB

HTML

<form name="EnqFrm" ng-app="EnqFrm" ng-controller="EnqController" ng-submit="save()">
<label>Class Days:</label>
<input name="chkweek" ng-model="formData.chkweek.Mo" type="checkbox">Mo
<input name="chkweek" ng-model="formData.chkweek.Tu" type="checkbox">Tu
<input name="chkweek" ng-model="formData.chkweek.We" type="checkbox">We
<input name="chkweek" ng-model="formData.chkweek.Th" type="checkbox">Th
<input name="chkweek" ng-model="formData.chkweek.Fr" type="checkbox">Fr
<input name="chkweek" ng-model="formData.chkweek.Sa" type="checkbox">Sa
<button id="btnSubmit" class="btn btn-default">SUBMIT</button>

AngularJS:

/* ANGULAR JS */
var weeksknm;
var app = angular.module('EnqFrm', []);
app.controller('EnqController', function ($scope, $http) {

    $scope.formData = {};

    $scope.save = function () {
        var url = "Controller/enq_postadmin.php";
        $http.post(url, $scope.formData).success(function (da) {
            alert(da);
            $scope.formData = "";
        });
    };

});

PHP:

<?php if ($_SERVER['REQUEST_METHOD']=='POST') {
    $data=file_get_contents("php://input");
    $inp=json_decode($data);
    echo $txtWeek=$inp->chkweek;
}
else {
    echo'try agian';
}
?>

Angular-leaflet-directive Custom HTML popup

I'm attempting to create a custom popup while using the angular-leaflet-directive. I'm opening the popup from the leaflet.draw on:create event. Here:

map.on('draw:created', function(e) {

    layer = e.layer;
    drawnItems.addLayer(layer);
    var newComment = "Enter Comment";
    var newID = "ID";
    var newGeoJsonFeat = layer.toGeoJSON();
    newGeoJsonFeat.properties = {"comment":newComment, "id":newID};
    console.log(newGeoJsonFeat);

    onEachFeature(newGeoJsonFeat,layer);
    layer.openPopup();
});

Then I'm using @blackjid's logic as seen here: http://ift.tt/1EPc6Qv to bind the custom popup

function onEachFeature(feature, layer) {
    // Create get the view template
    var popupContent = '<div ng-include="\'partials/popup_newfeat.html\'"></div>';
    console.log("assigning popup");

    // Bind the popup
    // HACK: I have added the stream in the popup options
    layer.bindPopup(popupContent,{
      closeButton: false,
      maxHeight: 300,
      feature: feature
    });
};

$scope.$on('leafletDirectiveMap.popupopen', function(event, leafletEvent){

  // Create the popup view when is opened
  var feature = leafletEvent.leafletEvent.popup.options.feature;

  var newScope = $scope.$new();
  newScope.stream = feature;

  $compile(leafletEvent.leafletEvent.popup._contentNode)(newScope);
});

Long story short, Everything works fine except the popup container isn't resizing properly to fit the new content. The height seems right, but the width is off.

I tried using:

.leaflet-popup-content {
    width:auto !important;
}

Which will probably suffice, but this causes the popup anchor to shift to the bottom left of the popup for some reason. AutoPan is also broken when clicking near the top of the map.

Does anyone know where and how I can get popup.update() to fire? I believe thats what needs to happen, but I don't know where to implement it. I've tried calling it after layer.openPopup() like so:

    onEachFeature(newGeoJsonFeat,layer);
    layer.openPopup();
    layer.getPopup().update();
});

But that doesn't seem to do anything. Any help is greatly appreciated!

How to pass value return from API into googlechart (AngularJS)

I want to pass value return from API into google chart, however, I cannot get the value. I got this "Table has no columns."

//map.html

<div ng-if="ctrl.postcode != 'Loading...' && !ctrl.noData" google-chart chart="ctrl.chartObject" style="{{cssStyle}}"></div>

//app.js

function GraphService() {
var chartObject = {
    "type": "LineChart",
    "displayed": true,
    "data": { },
    ....
}

//API

"avgpsf":{"2015-Q2":null,"2015-Q1":null,"2014-Q4":422.69000244141,"2014-Q3":590.6814226423,"2014-Q2":534.81999345259,"2014-Q1":480.51332600911},
"avgpsf2":{"2015-Q2":null,"2015-Q1":null,"2014-Q4":345.67999267578,"2014-Q3":null,"2014-Q2":371.60998535156,"2014-Q1":316.58000183105}

How to pass the value into data in app.js? @_@

Thank you!

How to reference package added by Bower?

In VS.NET 2015, I've added a reference in bower.json for angularjs. This caused the angularjs package to be downloaded, which I can see in the Bower folder.

However, I'm not able to execute any angularjs code. I do have an ng-app in the HTML tag. If I add a CDN reference to the angularjs library, it works fine.

What am I missing to use the package downloaded by Bower?

How to use ons-select in onse-ui-1.3.1?

i want to use ons-select in my app. and i have added it into my code, then debug the app, but the emulate show nothing. by the way, webstom alert me that 'can not find the ons-select tag'. so how to use ons-select in onse-ui-1.3.1? Any help is really appreciated.

ASP.NET Boilerplate Module Zero AbpAuthorize not working and /AbpScripts/GetScripts returns sever error

I just started developing a web application using ASP.NET Boilerplate Framework. Until I tried to implement authorization using module zero, it was working just fine. But now when I run the the web app it seems it is ignoring the AbpAuthorize attribute.

[AbpAuthorize]
public class DashboardController : MyWebAppControllerBase
{
    // GET: Dashboard
    public ActionResult Index()
    {
        return View("~/App/Main/views/layout/layout.cshtml");
    }
}

Also /AbpScripts/GetScripts returns

Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[MissingMethodException: Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.]
   Abp.Web.Authorization.<GetScriptAsync>d__2.MoveNext() +0
   System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(TStateMachine& stateMachine) +70
   System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start(TStateMachine& stateMachine) +14
   Abp.Web.Authorization.AuthorizationScriptManager.GetScriptAsync() +128
   Abp.Web.Mvc.Controllers.<GetScripts>d__0.MoveNext() +346
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212

What am I missing here? I tried to implement everything on the Module Zero sample project but it seems there is something I am missing.

Angular binding to service value not updating

I cannot get a binded service value to update when it is changed. I have tried numerous methods of doing so but none of them have worked, what am I doing wrong? From everything I have seen, this seems like it should work...

HTML:

<div class="drawer" ng-controller="DrawerController">
  {{activeCountry}}
</div>

Controller:

angular.module('worldboxApp')
    .controller('DrawerController', ['$scope', 'mapService', function($scope, mapService) {

        $scope.$watch(function() { return mapService.activeCountry }, function(newValue, oldValue) {
            $scope.activeCountry = mapService.activeCountry;
        });

    }]);

Service:

angular.module('worldboxApp').
    service('mapService', function(dbService, mapboxService, userService) {

    this.init = function() {
        this.activeCountry = {};
    }

    this.countryClick = function(e) {
        this.activeCountry = e.layer.feature;
    };

    this.init();
});

I put a break point to make sure the mapService.activeCountry variable is being changed, but all that ever shows in the html is {}.

CAS Authentication Filter AngularJS

I am looking to implement CAS server for SSO for my angularJS front end application and Rest Backend application. I have configured the CAS 4.0 web app and the management webapp and they are working properly. The part I am confused about is how Angularjs and the UI- router should interact with the CAS authentication filter?? I am using the CAS login page for authentication and am not able to figure out how this would work. I have looked for any documentation on this and was not able to find any solution.

Could anyone provide any direction??

Cannot call AngularJS controller function on page load

I would like to call Angularjs function on jQuery page load event. But always get undefined or failed.

Cannot figure out what is wrong in it.

My Plunker Test Page

Strange behaviour of angularjs with Float32Arrays

I have noticed some not so nice behaviour of angularjs when using Float32Array values.

Essentially I tested these three

angular.module("myApp", []).controller("myCtrl", function($scope) {
  $scope.n = 0.2; // Displays as 0.2
  $scope.arr1 = new Float32Array(1);
  $scope.arr1[0] = 0.2; // 0,20000000298023224
  $scope.arr2 = new Float64Array(1);
  $scope.arr2[0] = 0.2;  // Displays as 0.2
});

I do understand the problem with 0.2 being periodical as a binary fraction.

However, do you have any idea how to tell the toString method (or some other function) to take account for the lower precision and round the decimal when appropriate?

This is the directive that I added to make it a bit better (but still not quite):

.directive("numberfloat", function(){
  return {
    scope: {n: "=model"},
    template: '<input type="number" ng-model="m" ng-model-options="{getterSetter: true}"/>',
    link: function($scope){
      $scope.m = function(newVal){
        if(newVal){
          $scope.n = newVal;
        }
        return parseFloat($scope.n.toFixed(4));
      }
    }
  }
})

http://ift.tt/1EP6rde

GET error MEAN App

I've been learning how to use the MEAN stack in order to build web apps and so far it's been a lot of fun. Instead of using yeoman generators or npm app to generate my code for me, I've been building my whole app from the ground up. This way I know how each piece connects and what is going on with my app. I was just starting to connect the front and back end of my app when I looked at the developer console and saw

GET http://ift.tt/1JOZRb6

Not only angular, but every other resource I have (Modernizr, angular-routes, mootools, restangular, etc ...). When you use the yeoman angular generator you are suppose to run the grunt serve command to start up the angular side. Because I built the app from scratch and I am using npm for my build tool I didn't know how to build the front end server. So, I just went with a simple nginx virtual host pointing to my index.html. Here's the config:

server {
        listen 80;

        server_name blog.dev;

        root /home/michael/Workspace/blog/app;
        index index.html index.htm;

        location / {
                try_files $uri $uri/ =404;
        }
}

I'm not sure what other variables could be affecting the situation, so if I missed something please tell me and I'll be happy to give you what you need!

Connecting Ionic App to existing MEAN Stack 'sUser Auth

Based a project's api and user auth on a project by scotch (http://ift.tt/1wF0QPo). Generally same, but trying to build Ionic app that can use this existing user auth infrastructure.

Wondered if anyone had any suggestions.

Thanks!!!!

Canvas won't display

Working with Chart js and have run into a bit of trouble. I am trying to pull some data from a web service (which I am doing just fine) but when I try to place it into the chart, the chart doesn't display. I am pulling the data from here just fine. The console prints out the expected values, even the interval works to make sure nothing has changed.

Also the canvas div shows up on the page, just the chart doesn't animate. The html here is pretty straight forward, as I am just using it for a small widget:

  <body ng-app="myapp" ng-controller="MainCtrl">
    <div id="canvas-holder">
      <canvas id="chart-area" width="500" height="500"></canvas>
    </div>
    <button id="randomizeData">Randomize Data</button>
  </body>

And here is a plunker so you can better understand whats going on. If you view the console you can see there are no errors.

Thanks in advanced.

'dict' object has no attribute 'pk' Django Rest API Framework

Im using Django Rest API Framework, I want to upload multiple images for a single project using Angular js.

Here's my model:

class Project(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    owner = models.ForeignKey(User)
    number_of_photos = models.IntegerField()

class Photo(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    images = models.ImageField(upload_to='photos/', max_length=254)
    project = models.ForeignKey(Project)

I have this serializers:

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('id', 'created', 'number_of_photos', 'owner')

    def create(self, validated_data):
        project = Project.objects.create(**validated_data)
        return project

class UploadSerializer(serializers.ModelSerializer):
    project = ProjectSerializer(many=True, read_only=True)

    class Meta:
        model = Photo
        fields = ('url', 'created', 'images', 'project')

In my view I got this inside my viewsets.ModelViewSet

serializer = UploadSerializer(data=photo_array, many=True, context={'request': request})

if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

The variable photo_array contains:

[{'project': u'1', 'images': {u'name': u'test-image.png', u'lastModifiedDate': u'2015-04-22T08:51:11.000Z', u'webkitRelativePath': u'', u'lastModified': 1429692671000, u'type': u'image/png', u'size': 43152}}, {'project': u'1', 'images': {u'name': u'test.png', u'lastModifiedDate': u'2015-04-08T08:35:17.000Z', u'webkitRelativePath': u'', u'lastModified': 1428482117000, u'type': u'image/png', u'size': 127433}}]

But it gives me an error 'dict' object has no attribute 'pk'

Did my photo_array variable cause this problem?.

Angular - "No results" for a table

Was wondering if there is a simple way to have Angular show "No results"

For example:

<table>
  <thead>
    <tr><td>First Name</td><td>Last Name</td></tr>
  </thead>
  <tbody>
    <tr><td>Jonny</td><td>Bizzle</td></tr>
  </tbody>
</table>

Would become something like:

<table>
  <thead>
    <tr><td>First Name</td><td>Last Name</td></tr>
  </thead>
  <tbody>
    <tr><td colspan="2">No results</td></tr>
  </tbody>
</table>

If say $http.get() returns no names

Ng-if not hiding element when watched variable turns false

I am trying to hide an element based on the width of the screen and a test variable. I am running into an edge case where the ng-if directive is not properly hiding an element despite the value being false. Here are the relevant code snippets. The console log reports that my elemnt should be visible, however it is not showing up.

$scope.setContents = function(contents) {
    $scope.noteContent=contents;
    $scope.noteVisible=true;
    $scope.hideNoteList();
  }

$scope.checkWindowSize = function() {
    if ( $(window).innerWidth() < 768 ) {
      $scope.smallScreen = true;
      console.log("Window size is small");
      $scope.hideNoteList();
    }
    else {
      $scope.smallScreen = false;
      console.log("Window size is not small");
      $scope.hideNoteList();
    }
  }

$scope.hideNoteList = function () {
    if($scope.smallScreen && $scope.noteVisible){
      $scope.noteListVisible= false;
      console.log("Note List Should be Hiding");
    }
    else {
      console.log("Note List Should be Visible");
      $scope.noteListVisible= true;
    }
  }

$(window).load($scope.checkWindowSize);
  $(window).resize($scope.checkWindowSize);

HTML

<ul class="list-group col-xs-0 col-sm-6 col-md-4 col-lg-3" ng-if="noteListVisible">
<li ng-repeat="note in notes>
  <h2 ng-click="setContents(note.content)"></h2>
</li>

Nested/embedded $resources in ngRepeats

My API populates some nested models. Using a shopping example, when you query orders, the items property is populated with the description and quantity instead of returning just the item IDs.

orders: [
    {_id: 1,
     items: [
         {_id: 100,
          description: "apple", // from lookup in the Items table
          quantity: 4 // from lookup in the Items table
         }, ...
     ],
     ...
    }, ...
]

My view looks like:

<div ng-repeat="order in vm.orders">
    <ul ng-repeat="item in order.items">
        <li ng-model="vm.orders[$parent.$index].items[$index].description" ng-blur="item.$update()"></li>
        <li ng-model="vm.orders[$parent.$index].items[$index].quantity" ng-blur="item.$update()"></li>
    </ul>
</div>

The goal is to let the user update the item description and quantity from this view. (The lis are contenteditable directives.) The update call should be made on the Item $resource, not the Order $resource.

Is there a way to get Angular to recognize that the embedded documents are bona fide Items?

The workaround that I have is to change the ng-blur:

ng-blur="Item.update({_id: item._id})"

(If I do that, there's also no point in using the $parent.$index and $index syntax -- just order.item and item.description.)

Protractor: Storing URL in a variable to parse returns "undefined"

I've been trying to get the current URL and am wanting to cut out parts of the URL to use in another method. I've tried many ways, and one solution I saw online suggested using the beforeEach() method. I've been trying this and no matter what, this.urlString always returns undefined.

Heres what i current have. I must be missing something as to why this is returning undefined however I can't figure it out.

this.urlString;

beforeEach(function () {
  mainPO.navigateHome();
  mainPO.clickCurrent();

  browser.getCurrentUrl().then(function (url) {
    return this.urlString = url;
  });
});

console.log(this.urlString)

What I want to do is store the URL in a string, then parse the string to cut out everything before the ".com" of the URL so i can take the string and plug it into another URL for crawling to another link.

Fetching Angular Service Data

OBJECTIVE

Have Angular access a Service, retreive information, and display Service Information in two different controllers (later these controllers will manipulate this data, independently).

LIVE DEMO http://ift.tt/1IdTYSK

index.html

<html ng-app='plunker'>

<head>
  <title>AngularJS - Searching Text</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.min.js"></script>
  <script src="app.js"></script>
</head>

<body>
  <h1>Search & Reverse Text</h1>

  <h2>Original Sentence sent to Service</h2>
  <form>
    <input type='text' ng-model='value' placeholder='insert sentence' />
    <button ng-click='setString(value)'>Set</button>
    <pre>Sentence: {{value}} </pre>
  </form>

  <div ng-controller='myController1'>
    <h2>Controller 1 fetching from Service</h2>
    <pre>{{fetch1}}</pre>
  </div>

  <div ng-controller='myController2'>
    <h2>Controller 2 fetching from Service</h2>
    <pre>{{fetch2}}</pre>
  </div>


</body>

</html>

app.js

var app = angular.module('plunker', []);

/*Service to pass data between controllers */
app.service('passData', function() {
  $scope.stringValue = {};

  $scope.getString = function() {
    return stringValue;
  },

  $scope.setString = function(value) {
    stringValue = value;
  }
});

/* Controller1 catched string from  original sentence */
app.controller('myController1',['passData', function($scope) {
  $scope.fetch1 = passData.getString();
}]);

/*Controller2 catched string from  original sentence */
app.controller('myController2', ['passData', function(scope){
  $scope.fetch2 = passData.getString();
}]);

QUESTIONS

  1. How can I check if the service is catching the original sentence?
  2. Why is it that both {{fetch1}} and {{fetch2}} aren't displaying properly?
  3. Is this a proper use of services interacting with controllers? Are there better ways?

add/remove carousel items during runtime within an Angular app

Folks: building a simple Angular app consisting of a page with thumbnails - each thumbnail contains a 'star this' link. You click the star, the thumbnail appears within a carousel in the header and vice versa when you click off the star.

Issue: I've been looking into angular carousels such as cardflow, slick carousel and flexsider but having problems when dynamically adding new slide items into the carousel.

Template:

<div class="carousel-container">
   <slick dots="true" center-mode="true" infinite="true" speed="300" slides-to-show="2" touch-move="false" slides-to-scroll="1">
      <div class="slider" ng-repeat="file in myLocalRepoStarred" ng-if="file.event.starred == 1" >
          <img class="carousel-img" ng-src="docs/{{file.event.id}}/{{file.event.dl_thumb}}"/>
      </div>
  </slick>
</div>

Basically, when a thumbnail is 'starred', a custom directive is used with an on click which updates the $scope object myLocalRepoStarred setting a property starred to 1. Changes to $scope are applied then picked up in the template..

Question: When the new slide item gets added within ng-repeat, it messes with the carousel layout, styling etc because it hasn't got the appropriate classes, attributes applied (as these get added when the page initially loads).

Has someone faced a similar problem? If so, how did you get around it? Are there any more suitable plugins to achieve this?

edit: see comment below for the eventual fix..

Which library to choose: AngularJS Dynamic Form Generation based on JSON Schema

I am planning to build a generic Web + Desktop + Mobile solution for organizations that heavily do surveys and data collection and generate reports based on collected data (e.g. Non Profits).

The solution needs to be centrally controlled and synced, can work offline and can be used on any device supporting HTML5.

Dynamic Form Generation will be a core functionality for this product. I've been looking for a library that supports generating mobile ready forms. Given AngularJS + Bootstrap are promising in this regard, I came across:

  1. formly-js/angular-formly
  2. Textalk/angular-schema-form

which looked popular on GitHub Explorer and seemed very mature to provide the desired functionality. I need guidelines to which to choose, or should I go for some other solution?

If you have experience working on such a project, what would you suggest me, which technology stack should I use, given the following aspects of the product:

  1. As mentioned the product should run on any HTML5 supported device.
  2. Forms and Data access can be controlled from server/cloud per user.
  3. App should work offline and when finds internet, should sync collected data with server/cloud.
  4. There will be a form designer for Administrators to visually build forms and any newly designed form should instantly get available to data entry devices.
  5. Collected forms data will be used to generate Reports (Publish to Web, Excel, Interactive Charts etc.).

To address Offline behavior, Controlled Access, Syncing and HTML5 support, Sencha Space looks compelling, any thoughts?

Modify input field value via simulated keypress in Karma

Using Karma + PhantomJS, I'm testing an Angular directive that involves form fields. I need to trigger keypress events on an input field so that the value, $dirty, and $valid scope values are properly set.

Keypress events don't appear to actually change the value or validation settings, they.

If there's no way to simulate entry, is there a way I can manually trigger the dirty flag, and validation checks (after setting the value).

These tests are for individual components and are separate from what we're using Protractor to test.

Angularjs - ng-map - Google Maps Javascript API v3 - how to Set best Zoom for Multiple markers

I'm using ngMap in an angularjs app. Iam displaying google-map with multiple markers onclick of Open map! button and first address present in the addresses array im taking as map center.

Here is The Plunk

All address related markers are displaying fine.

But how to set best zoom automatically for array of addresses, here these addresses i'm fetching from database, so these addresses changes for each request based on some condition.

How to set up environment variables for MEAN stack?

I just followed a MEAN stack tutorial to build a demo app. A hard-coded JWT secret 'SECRET' was used for authentication and the tutorial notes you should implement this as an environment variable instead of hard-coding it (makes sense). How does one do this?

The relevant portions of code are in models/Users.js:

var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');

var UserSchema = new mongoose.Schema({
  username: {type: String, lowercase: true, unique: true},
  hash: String,
  salt: String
});

// ...

UserSchema.methods.generateJWT = function() {
    var today = new Date();
    var exp = new Date(today);
    exp.setDate(today.getDate() + 60);
    return jwt.sign({
        _id: this._id,
        username: this.username,
        exp: parseInt(exp.getTime() / 1000)
    }, 'SECRET');  // <----
};

mongoose.model('User', UserSchema);

And in routes/index.js:

var express = require('express');
var router = express.Router();
var passport = require('passport');

var jwt = require('express-jwt');
var auth = jwt({secret: 'SECRET', userProperty: 'payload'}); // <----

var mongoose = require('mongoose');
var User = mongoose.model('User');

// ...

How to make 'SECRET' an environment variable?

Thanks in advance.

Angular JS Binding Waiting Until Input

I'm working with Angular JS and Socket.io in an attempt to develop a simple chat room. I got the client side working great when not plugged into sockets. After I added the socket communication, however, the binding is messing up.

I type in the message and hit send. addMessage is fired and then the 'chat message' socket event is fired. However, the UI does not get updated until I type another letter or click send again. Then the binding works its magic and the UI adds the message.

Any ideas?

js file

//Receive Socket message.
//Runs but UI does not update.
//UI updates on user's next input
$scope.socket.on('chat message', function(msg) {
    var message = new Message(msg);
    $scope.messages.splice(0, 0, message);
    $scope.clear();
});

//Add Message, sends to socket
$scope.addMessage = function () {
  if($scope.validate()) {
    var message = new Message($scope.message);
    $scope.socket.emit('chat message', message.text);
  }
};

html file

<form role="form" ng-submit="addMessage()">
    <div class="row">
        <div class="input-group" style="margin-bottom: 5px;">
            <input type="text" ng-model="message" placeholder="What's up?" class="form-control" ng-change="validate()">
                <span class="input-group-btn">
                    <input type="submit" class="btn btn-primary" value="Add"/>
                </span>
            </input>
        </div>
    </div>
</form>
<div ui-sortable ng-model="messages">
    <div ng-repeat="message in messages"  style="padding:5px 10px;">
        <p>{{ message.text }}</p>
    </p>
</div>

How to make the http request in Angular in my case?

I am having an issue loading a $resource object in my case.

I have something in parent controller like

$scope.data = Product.$query();

then in the child controller, I have

$scope.data.then(function(product){
     console.log(data);
})

My factory

angular.module('testApp').factory('Product', ['$resource', function ($resource) {
    return $resource('/api/product');
}]);

I am getting $scope.data.then is not a function error in my child controller I am not sure what's going on here. Can someone help me about it? Thanks a lot

How to destroy a ui-grid?

Is there any built in method available to destroy the ui-grid (angularjs) and reload it again. When i reload the grid data using ajax call it is reloading the new data, but it is not resetting the current page number (paginationCurrentPage) and paginationPageSizes

How to access Nested JSON Data via Index, Angular JS, ng-click?

I have a List of cars assigned to a person for a particular month. If you search April you will get April data. How do I access Nested JSON data via Index?

Here's plunker

   $scope.cars = $scope.results[resultIndex].cars.map(function(car) {
          return {
        make: car.Make,
            year: car.Year
          };
        });

   $scope.showCars = function(resultIndex) {
      $scope.cars = $scope.results[resultIndex].cars;
    };

Nested ui-view in angularjs

Hello i am trying to do something here but it does not work, i have the following view:

<header ui-view="header">

</header>

and i my app.js file:

.state('root', {
    url: '',
    views: {
        'header': {
            templateUrl: '/js/app/partials/layout/header.html',
            controller: 'HeaderController'
        },
        'slider': {
            templateUrl: '/js/app/partials/slider.html'
        },
        'container@': {
            templateUrl: '/js/app/partials/home.html',
            controller: 'HomeController'
        },
        'sidebar': {
            templateUrl: '/js/app/partials/layout/sidebar.html',
            controller: 'SideBarController'
        },
        'footer':{
            templateUrl: '/js/app/partials/layout/footer.html'
        }
    }
})

Now this particular view:

'slider': {
    templateUrl: '/js/app/partials/slider.html'
},

is not in my index.html file but rather within my /partial/layout/header.html file. Now the header template is being loaded into the header view, but the slider view does not show.

This is my header.html partial with my slider view inside:

<div class="container-fluid">
    <div class="col-md-12">
        <a href="#" class="pull-left">
            <img src="images/logo.png" alt="Your Happy Family" class="img-responsive">
        </a>
        <!-- Begin Top Navigation -->
        <div class="menu_block">
            <nav class="horizontal-nav full-width horizontalNav-notprocessed">
                <ul class="sf-menu">
                    <li class="home"><a ui-sref="root.home">home</a></li>
                    <li class="tickets">
                        <a href="#">tickets</a>

                        <ul>
                            <li class="bus"><a href="#">Bus</a></li>
                            <li class="airline"><a href="#">Local Airline</a></li>
                            <li class="events"><a href="#">Events</a></li>
                        </ul>
                        <div class="clear"></div>
                    </li>
                    <li class="partners"><a ui-sref="root.partners">partners</a></li>
                    <li class="contact"><a ui-sref="root.contact">contact us</a></li>
                </ul>
            </nav>
            <div class="clear"></div>
        </div>
        <!-- End Top Navigation -->
        <div class="clear"></div>

        <!-- Slider View -->
        <div ui-view="slider">
        </div>

        <div class="clear"></div>
    </div>
</div>

I am doing this for a reason, i need my slider view to appear within the header section, i would like some help with this, please let me know if you need further clarification of what i want to do.