Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Wednesday, November 12, 2014

angular infinite $digest loop error solution

I used ui.router and someday i found out
error console show me this error

10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $locationWatch; newVal: 32; oldVal: 31"],["fn: $locationWatch; newVal: 33; oldVal: 32"],["fn: $locationWatch; newVal: 34; oldVal: 33"],["fn: $locationWatch; newVal: 35; oldVal: 34"],["fn: $locationWatch; newVal: 36; oldVal: 35"]]

and I debug for whole day and gave up.

after debugging, I seached on internet and many people face with this problem.

and I finally fix the error

Before if I used location.href='#/xxxxxx'
and changed is $location.path(realpath);

Monday, October 13, 2014

Element ready after appending data.

In jquery, there I can catch callback when data is fully loaded .

I wanted to knwo maybe in angularjs has too.
I searched much time and find out how to use
below is just example.


angular.element(document.querySelector('#contentBox')).append(data).ready(function(){
//                alert('ready complete');
         $scope.loaded();

});


and 

angular.element i can use jquery lite 
reference by 

Sunday, October 5, 2014

angular ng-if

how can I check if data is over number or like when in jstl
there i can use ng-if

for example .


referenced by https://code.angularjs.org/1.1.5/docs/api/ng.directive:ngIf

  1. <span ng-if="checked" ng-animate="'example'">
  2. I'm removed when the checkbox is unchecked.
  3. </span>

Thursday, September 18, 2014

My Thought about AngularJs

I used it for a half year.

First time I started it~ It was amazing because each input or text automatically know data is changed.

and I wanted know more and more ~

I will write what is very difficult to be skillful

Difficult Thing
  - understanding directive.
  - directives are very difficult to study
    scope, link, compile, restrict, transclude and so on...
  - communication controllers, controllers inherit
  - services

if I'm familiar with angularjs

Usefull Thing
  - project speed is upup ~
  - easy ajax network and databinding
  - custom common directives and i can use it
  - one page app
  - MVC structure

Wednesday, September 17, 2014

Directive example

directive

1. restrict

A 엘리먼트
E 속성
C 클래스


2. template or templateUrl

실제로 들어가게 되는 div

3. 특징
- directive는 새로운 scope를 생성할 수 없다
- scope를 부모로 부터 상속을 받는다
-

app.directive('helloWorld', function() {
  return {
    restrict: 'AE',
    replace: true,
    template: '<p style="background-color:{{color}}">Hello World',
    link: function(scope, elem, attrs) {
      elem.bind('click', function() {
        elem.css('background-color', 'white');
        scope.$apply(function() {
          scope.color = "white";
        });
      });
      elem.bind('mouseover', function() {
        elem.css('cursor', 'pointer');
      });
    }
  };
});

4. link fuction
- link에는 3개의 변수가 들어간다
- scope는 parent 스코프

5. scope의 종류는 두가지가 있다
- A child scope     -> scope:true
- An isolated scope -> scope:{}

childe scope 는 부모로부터 scope를 상속받는다
isolated scope 는 개별적으로 하나를 생성한다.

isolated scope는 부모의 scope를 사용할 수 없는것이 아니다.

6. @ 사용하기 (데이터 바인딩용)
- @ for One Way Text Binding
- 상위 컨트롤러의 color가 바뀌면 하위의 내용도 따로 바뀐다.

app.directive('helloWorld', function() {
  return {
    scope: {
      color: '@colorAttr'
    },
    ....
    // the rest of the configurations
  };
});


<body ng-controller="MainCtrl">
  <input type="text" ng-model="color" placeholder="Enter a color"/>
  <hello-world color-attr="{{color}}"/>
</body>


7. = 사용하기 (데이터 바인딩용)
= for Two Way Binding

app.directive('helloWorld', function() {
  return {
    scope: {
      color: '='
    },
    ....
    // the rest of the configurations
  };
});


8. & to Execute Functions in the Parent Scope

app.directive('sayHello', function() {
  return {
    scope: {
      sayHelloIsolated: '&amp;'
    },
    ....
    // the rest of the configurations
  };
});

<body ng-controller="MainCtrl">
  <input type="text" ng-model="color" placeholder="Enter a color"/>
  <say-hello sayHelloIsolated="sayHello()"/>
</body>



9. Parent Scope vs. Child Scope vs. Isolated Scope

Parent Scope : scope:fasle default
childe scope : scope:true   inherit parent scope
isolated scope :


10. The controller Function and require
app.directive('outerDirective', function() {
  return {
    scope: {},
    restrict: 'AE',
    controller: function($scope, $compile, $http) {
      // $scope is the appropriate scope for the directive
      this.addChild = function(nestedDirective) { // this refers to the controller
        console.log('Got the message from nested directive:' + nestedDirective.message);
      };
    }
  };
});

4번째 변수는 require 한 컨트롤러가 삽입된다.

app.directive('innerDirective', function() {
  return {
    scope: {},
    restrict: 'AE',
    require: '^outerDirective',
    link: function(scope, elem, attrs, controllerInstance) {
      //the fourth argument is the controller instance you require
      scope.message = "Hi, Parent directive";
      controllerInstance.addChild(scope);
    }
  };
});



reference site : http://www.sitepoint.com/practical-guide-angularjs-directives-part-two/

Tuesday, September 16, 2014

call Angularjs Scope from javascript fn

I found out that how I call angularjs scope's function from javascript

example is blow

angular.element(document.getElementById('yourControllerElementID')).scope().get();

Thursday, September 11, 2014

angularjs How to use Custom Select

what i just tell you is this is just one of many example and
I used it

so this is one way, not a solution of using it


<div class="sel_area" style="width:40%;">
                            <button class="btn_sel" type="button"  ng-click='showDropdown()'>
                                             {{selectedCondition.name}}
                            </button><span class="caret"></span>
                            <select id='searchCondition' ng-model='selectedCondition'
                            ng-options="condition.name for condition in conditions"
                            style='opacity: 0; width:0px; float:left;' >
  <option value='이름'>이름</option>
  <option value='전화번호'>전화번호</option>
  <option value='id'>id</option>
</select></div>


$scope.conditions = [
                         {name:'이름', shade:'light'},
                         {name:'전화번호', shade:'dark'},
                         {name:'아이디', shade:'dark'}
                       ];
        
$scope.selectedCondition = $scope.conditions[0];
        
$scope.showDropdown = function () {
        var event;
        
        var element = document.getElementById('searchCondition');
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('mousedown', true, true, window);
        element.dispatchEvent(event);
};

Wednesday, June 18, 2014

angular $stateProvider how to check if url is changed

there are ways to check if stateProvider is changed

1. $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams){

});

and also you can watch $locationChangeStart ..

I linked detail page below


https://github.com/angular-ui/ui-router/wiki#state-change-events

Friday, March 28, 2014

Call Parent Controller Function from Child Controller

in Nested Div you can call child function to call parent

this structure is a kind of java extend



<body ng-controller="MainCtrl">
  <div ng-controller="ChildCtrl">
    <!--because the ChildCtrl's $scope inherits from its parent $scope,
    properties and methods of both are available in my view-->
    <p>Hello {{firstName}} {{surname}}!</p>
    <p>Meaning of Life is {{addOne(41)}}.</p>
    <p ng-click='callP()'>Studies have shown {{multiplyByOneHundred(6/10)}}% of beginners are confused about inheritance.</p>
  </div>
</body>


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

app.controller('MainCtrl', function($scope) {
  $scope.firstName = 'Harvey';
  $scope.addOne = function(number){
    return number + 1;
  }
  $scope.show = function(number){
    alert('show2');
  }
});

app.controller('ChildCtrl', function($scope) {
  $scope.surname = 'Man..fren..gen..sen';
  $scope.multiplyByOneHundred = function(number){
    return number * 100;
  }
  $scope.callP = function(){
    $scope.$parent.show();
  }
  $scope.show = function(number){
    alert('show1');
  }
});

ng-include dynamic change view and controllers

this story is a sample
when you want change view and controllers

this is a good example


<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <style type="text/css" media="all">
      .controller-a {background-color: yellow;}
      .controller-b-style {background-color: lightgrey;}
    </style>
  </head>

  <body data-ng-app="webApp">
    <h1>Hello Plunker!</h1>
    <div class="controller-a" ng-controller="ControllerA">
      Controller A
      <div>
        <button ng-click="cntPlusPlus()">cnt++</button> CNT: {{cnt}}
      </div>
      <button ng-click="addB()">Add B</button>
      <div ng-repeat="B in Bs">
       <div ng-include="B.name"></div>
      </div>
    </div>
    <script type="text/ng-template" id="b-template">
   
      <div ng-controller="ControllerB">this is controller b: <button ng-click="cntPlusPlus()">cnt++</button></div>
    </script>
    <script>
      var webApp = angular.module("webApp",[]);
   
      webApp.controller("ControllerA", function($scope){
        $scope.cnt = 0;
        $scope.cntPlusPlus = function(){
          $scope.cnt++;
        };
     
        $scope.Bs = [];
        $scope.addB = function(){
          $scope.Bs.push({name:'b-template'});
        };
      });
   
      webApp.controller("ControllerB", function($scope){
        $scope.cntPlusPlus = function(){
          console.log("overwrite plus plus");
         // $scope.$parent.$parent.$parent.cnt++;  //should be moved to service
         alert('요소');
        }
      });    
    </script>
  </body>
</html>

Monday, March 24, 2014

Communication Between Controllers~!

This is the way that
how Controllers are communicating with each other

summary
call $rootScope.$broadcast of Service and
   other controller will listen $scope.$on





1. Service Registation 

var app= angular.module('myApp', ['onsen.directives', 'ngTouch']);
app.factory('messageService', function ($rootScope) {
    var messenger = {
        messages: [],
        identity: 0,

        addMessage: function (tab) {
            $rootScope.$broadcast('messageAdded', tab.url);
        }
    };
    return messenger;
});

2. Controller Sending

app.controller('titleCtrl', ['$scope','messageService',  function ($scope, messageService) {

 $scope.onClickTab = function (tab) {
            $scope.currentTab = tab.url;
            console.log('dd');
            messageService.addMessage(tab);

            

        }
}

2.  Controller Receiving

app.controller('tabsCtrl', ['$scope', function ($scope, myService) {
$scope.$on("messageAdded", function (event, args) {
            console.log('myEvent');
            console.log('args : ' + args);
            $scope.currentTab =args;

        });
}

Thursday, January 23, 2014

Big Hompage with Angular and RequireJS (MVC Pattern)

In the past, usually we made webpage multipages
in each page we have <script></script> tags if we need module
so each page needs to load all scripts that pages need
So it spend a lot of time and make people see loading bar as long as script are loaded

In present. web page trend is changing  step by step

today i want to share how to efficiently make big single webpage with angularJS and RequireJS

First Version


This Structure of this project is below screen shots

1. Angualr MVC Model



- explain 
1. view: view is only are consis of html files using angular js tags
2. router : this is routing url to which html should be loaded
3. Controllers : this controlls services and logic after views are loaded
4. service : these are functions that load json datas from server using ajax



2. RequireJS Dependency


- explain 

1. angular : this is angular library
2. angular-route : this is angular plugin, 
once angular under 1.0.8? I'm not sure angular library contatin route
3. angular-start : this defines route module
4. controller-start : this defines controllers 
5. route-start : this defines url routing patterns
6. service-start : this defines services related to this project




3. source Review

3-1. this project tree structure



3-2. main.html 

- <div ng-view></div> is the frame that html pages are changed into
- <script data-main="js/main"  src="js/libs/require.js" ></script>  
   first main.js will be called






3-3 main.js



3-4 angular-start(angular-init.js)
- define angular










3-5 controller-start(controller-init.js)

- you can use static controller and dynamic controller
 static controller : router will directly mapping html
 dynamic controllers : router will mapping using url patterns



3-6 router-start(routing.js)

/view/:id is mapped with static controller

/:cate/:sub is mapped width dynamic contollers



3-7 service-start(service-init.js)




4. get Service from controller 
mailListController.js

- getting mailService from services tray
- using mailService function














5. I cannot fully explain all source
later I will share my Project samples 


if you need right now reply and write you email

Have a good job

Wednesday, January 22, 2014

AngularJs Tutorial~

Below link is a tutorial that I made before

you can see the result in sample page

that html page will provide you edit, updatesource and update result

have fun~

hope to help you~