顯示具有 AngularJS 標籤的文章。 顯示所有文章
顯示具有 AngularJS 標籤的文章。 顯示所有文章

星期一, 2月 13, 2023

Angular 1.5 取得表單變數與重設

 常見需要在submit後reset表單的狀態與所有欄位重置預設值參考:

取得表單變數

$scope.initContactForm = function(contactName){
logger.debug('initContactForm');
$scope.contactForm = contactName;
};


重設


$scope.restart = function(){
logger.debug('restart');

$scope.contactForm.$setPristine();

$scope.isShowThanks = false;

//reset
$scope.contact = {
type: '0',
name: null,
mobilePhone: null,
meetdate: null,
meettime: '9:00',
company: '明久家具嘉義店',
jobTitle: null,
email: null,
title: null,
content: null //base64 encode
};
};

星期四, 6月 10, 2021

Angular 1.5 觸發表單驗證

常用的方法,簡單的表單驗證由控制器觸發


//submit後觸發驗證
$scope.validateByManual = function(form) {
logger.debug('validate');
angular.forEach(form, function (control, name) {

// Excludes internal angular properties
if (typeof name === 'string' && name.charAt(0) !== '$') {

logger.debug('field name:' + name);
// To display ngMessages
control.$setTouched();
control.$setDirty();

// Runs each of the registered validators
control.$validate();
}
});
}

星期日, 3月 26, 2017

[AngularJS] hide select的空字串值

常常會需要把select選單預設指定一個預設值,
但又不需要秀空字串的選項,只要設定一個ng-hide="true"就可以搞定。
常忘了,記錄一下。

星期一, 1月 04, 2016

[AngularJS] i18n 使用筆記

記錄一下angular translate的使用快速筆記。

環境設定

請引用angular-translate.min.js
使用模組 pascalprecht.translate

語言檔

透過 $translateProvider新增多國語系檔對應的內容,你可以另存以下的js至zh_TW.js檔
angular.module('myApp.controllers').config(function ($translateProvider) {
 $translateProvider
 .useSanitizeValueStrategy('escaped')
 .translations('zh_TW', {
  TRANSLATION_ID: 'Hello world !!',
  TRANSLATION_ID_2: 'Hello world !! {{value}}',
  TRANSLATION_ID_3: 'Hello world !! {{value1}},{{value2}}',
 });
});

$translate service處理多語系

  $translate('').then(function(translation) {
                    //translation為取得的鍵值

                });


Filter處理多語系

{{ 'TRANSLATION_ID' | translate }}


動態取代多國語言參數


使用filter
{{ 'TRANSLATION_ID_2' | translate:'{"value": 'Ken' }' }}

使用filter與多個參數
{
'TRANSLATION_ID_3': 'Hello world !! {{value1}},{{value2}}'
}

如果要多參數時,請在新增一個json變數至scope,如 $scope.translationData = {value1: 'Ken',value2: 'Ken2'}

{{ 'TRANSLATION_ID_3' | translate: translationData }}

使用directive表示式 在元素內透過translate與translate-values二個directive進行資料繫結

translate="TRANSLATION_ID_3" translate-values="{ value1: translationData.value1,value2: translationData.value2 }

事件

可以取得當語言變更的事件
$rootScope.$on('$translateChangeSuccess', function () {

// Language has changed
 });

啟動app設定語言方法

myApp.config(['$translateProvider','$windowProvider',
    function($translateProvider,$windowProvider) {
    var defaultLanguage = 'zh_TW';//你定義的語系檔名稱
    $translateProvider.use(defaultLanguage);
}])



星期六, 6月 13, 2015

[AngularJS] 不透過type=reset來清除表單

記錄一下如何在angular清除表單內的值呢?
一般來說除了透過在頁面上放置一個按鈕類型為reset的效果最快。
但如果要在送出表單後,Server確定新增正確後,
再清除表單可自已新增一個resetForm的方法來處理。
以下是一個新建用戶的頁面來說明:


重設2按鈕是使用自訂的方法來清除表單資料,這裡需要額外注意type=mail資料驗證失敗是不會被寫入進$scope的,透過手動來清除,透過上圖可以清除看到$scope.user物件並無存到已輸入的錯誤文字

 $scope.resetForm = function(formModel) {
            logger.debug('resetForm');
            console.log(formModel);


            $scope.addForm.$setPristine();
            angular.copy({}, formModel);

            $scope.user.email = '';//解決email input無法清除的問題,email欄位要在通過規則後才會被model綁定
        };

頁面元素放入 ng-click="resetForm(user),user則為表單的物件
  <button type="button"
                                 ng-click="resetForm(user)" class="btn btn-default">
                                <i class="fa fa-refresh"></i> 重設2</button>

星期六, 4月 11, 2015

[AngularJS-3rd] UI-Router 常用筆記

本篇慢慢記錄UI-Router相關的操作心得

UI-Router $state帶參數轉頁

  
$state.go('admin.productlist.uuid', 
{
uuid: product.FD_CurrentFilePathHash
});
 
// Admin page for productlist/:uuid
   $stateProvider
    .state('admin', {
     abstract: true,
     template: "",
     data: {
      authorizedRoles: [USER_ROLES.admin]
     }
    })
.state('admin.productlist.uuid', {

    /*manage user page */
    url: '/productlist/:uuid',

    views: {

     // the main template will be placed here (relatively named)
     // replace unnamed view '
' in this state's parent state, 'home'. '': { templateUrl: 'partials/global.index.html' }, //viewname@statusname // the child views will be defined here (absolutely named) 'header@admin.productlist': { templateUrl: 'partials/global.header.html', controller: 'HeaderCtrl' }, 'main_body@admin.productlist': { templateUrl: 'partials/product_dm/productlist.body.html', controller: 'ProductListCtrl' }, // for column two, we'll define a separate controller 'footer@admin.productlist': { templateUrl: 'partials/global.footer.html' } }, data:{ pageTitle: '產品DM' } });

星期五, 4月 10, 2015

[AngularJS] 小踩雷筆記: select option 綁定

當我們使用select做資料綁定的時候,需要注意一下綁型的變數型別是什麼字串或數值。
今天遇到的問題是,從db撈回來的select 設定的值是字串(String),但元件上綁定為數值(Int)
所以在設定model綁定的時候忘記轉成字串,就會發現綁定失敗XD

示意圖(圖好像合成錯張了,紅色是這次的注意的重點)


星期四, 4月 09, 2015

[UI-Bootstrap] 小踩雷筆記 Tabset元件的scope操作

記錄一下使用Tabset取得控制child scope變數的筆記:
由於Tabset會建立child scope,
所以想要存在tab內部的scope變化除了用 $parent.scope變數 (如果又巢狀的scope可能會發生錯誤例外),
也可以在parent controller宣告一致的變數,就能方便取值了。
以下這個Tabset的範例可以參考:
http://plnkr.co/edit/vclolFBfF7QMQAQgNmiL?p=preview


範例目的:
Justified這個tab裡面的input,一但值被改變,外面的parent scope會一起連動。




在tabset內綁定了一個parent scope宣告的model(model.selection)
<div ng-controller="TabsDemoCtrl">
  {{model.selection}}
  <tabset>
    <tab heading="Justified">
      <input ng-model="model.selection">
    </tab>
  </tabset>
</div>



宣告一個model的物件在parent scope,所以當tab裡面的input變動時,就容易取到變動的值了。
angular.module('plunker', ['ui.bootstrap']);
var TabsDemoCtrl = function ($scope) {
  $scope.tabs = [
    { title:"Dynamic Title 1", content:"Dynamic content 1" },
    { title:"Dynamic Title 2", content:"Dynamic content 2", disabled: true }
  ];

  $scope.model = {selection: ''};
  $scope.options = ['a', 'b', 'c', 'd'];

  $scope.alertMe = function() {
    setTimeout(function() {
      alert("You've selected the alert tab!");
    });
  };

  $scope.navType = 'pills';
};


https://github.com/angular/angular.js/wiki/Understanding-Scopes
https://github.com/angular-ui/bootstrap/issues/1553

星期五, 4月 03, 2015

[AngularJS] 多個信箱驗證的directive實作

記錄一下多個信箱驗證的directive實作。
.directive('multimails', function() {

    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl, ngModel) {

            var validator = function(value) {
                // console.log('validator: ' + value);
                if (value != '' && typeof(value) != 'undefined') {
                    var splitMailsArr = value.split(';');
                    // .filter(function(el) {return el.length != 0});
                    for (var i = 0; i < splitMailsArr.length; i++) {
                        var currMail = splitMailsArr[i];
                        // console.log('currMail: ' + currMail);
                        if (currMail != '') {
                            if (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(currMail)) {
                                ctrl.$setValidity('multimails', true);
                                // console.log('pass');

                            } else {

                                ctrl.$setValidity('multimails', false);
                                // console.log('no pass');
break;
                            }
                        }

                    }
                    return value;

                }

            };

            //驗證規則的順序
            ctrl.$parsers.unshift(validator);
            ctrl.$formatters.unshift(validator);
        }
    };
})

星期五, 3月 27, 2015

[AngularJS] 小踩雷筆記: ng-class的css name使用-符合

如果你的class name使用了-符號,搭配使用ng-class時,請加上''符號,不然則會失效
請參考: http://stackoverflow.com/questions/15557151/ngclass-style-with-dash-in-key
After hours of hacking around, it turns out the dash gets interpolated! Quotes are needed.
 class="icon-home" ng-class="{'icon-white': someBooleanValue}">
I hope this helps someone from tearing their hair out.
UPDATE:
In older versions of Angular, using a backslash also does the trick, but not in the newer versions.
 class="icon-home" ng-class="{icon\-white: someBooleanValue}">
The former is probably preferred, since you can search for it in your favorite editor.

星期六, 3月 14, 2015

[AngularJS] 小踩雷筆記: button鈕點擊一直發生submit form的動作

今日踩雷小筆記: 如果你在form表單裡放了button鈕,並自行綁定ng-click方法時,如果html的button忘記加入type="button", angular將會貼心幫你觸發form submit XD

星期五, 2月 06, 2015

[Angular] ng-src造成的infinite loop

目前在介面上顯示圖片列表時,因為圖片的網址加了random的參數來解決cache的議題,
但會產生infinite loop的error,打開console可以看到。
找到了Stackoverflow以下解譯這個的原因。

http://stackoverflow.com/questions/17222526/angular-js-in-ng-src-causes-infinite-loop
Well I think the problem is the getRandom function returning a different value every time it's called. Here's what happens:
  1. Angular call your function
  2. Gets the value
  3. See's it's different from the previous value
  4. Marks the cycle as dirty
  5. After the cycle is finished it re-runs the cycle thus getting a new value ...
The idea would be to have getRandom give discreet values over a period of time. For example only give a new value every 1, 10, 30 sec whatever you see fit.
This advice applies to many things, actually. Angular provides no guarantees about how many times it will call your functions that are found in bindings. So you need to make them fast and also you need to make sure that for the same input they return the same output(most times, though in this case it might be justified).
Also consider exactly when/how the image might change and if the actual changes can be triggered by something else consider only creating a new result value for getRandom only when the actual changes are triggered(ex: user uploads a new profile image, a timer executes, etc)
UPDATE: Can't replicate it in plunker using Chrome

解決的方法可以利用一個timer來透過記錄上一次變更的時間差來避免一直檢查的問題。




$scope.lastMillis = new Date().getTime();
     $scope.getRandom=function(){
         var curMillis = new Date().getTime();
         if (curMillis-$scope.lastMillis>5000) {
             $scope.lastMillis = curMillis;
         }
         return $scope.lastMillis;
     };

星期日, 11月 02, 2014

[AngularJS] Retrieve JSON Data的key與data

一般使用ng-repeat的時候,除了有一般Array的結構之外,
有時API回傳的結果可能需要透過JSON DATA內部的Key結構來綁定。

今天的Case是要綁定一個問卷:D 資料結構長這個


為了讓元素的name id不一致也用了nested ng-repeat如何拿$index的方法,範例如下:

使用ng-init可以將第一層的迴圈$index透過 qTitleIndex取得
    

    <form id="investQuestionnaireForm">
     <div id="investQuestionnaireList"
      ng-controller="MyQuestionnaireCtrl" class="dialog-moduleContent msgBoxDetail">
   <div class="question-list">
    <ul >
     <li ng-repeat="(qTitle, ansList) in questionnaireList"
      ng-init="qTitleIndex = $index">
      <div>{{qTitle}}</div>
      <ul class="answerlist">
       <li ng-repeat="ans in ansList">
        <input type="radio" name="{{qTitleIndex}}_ans_{{$index}}" value="{{ans}}" /> {{ans}} <br/>
       </li>
      </ul>
     </li>
    </ul>

   </div>
     </div>
最後示意
 

星期六, 11月 01, 2014

[AngularJS] 使用jquery來呼叫Angular scope 方法與更新變數

想在舊的jQuery專案內呼叫Angular的方法與變數,可以在jquery中使用以下方法取得scope

var ngScope = angular.element(document.getElementById('元素ID')).scope();

ngScope即可以操作原本在ng內的方法與變數了,在透過jquery更新完變數後,記得要呼叫$apply來告知Angular裡面的變數的值已改變了!!

參考以下完整範例:



星期五, 8月 15, 2014

[AngularJS] 自訂directive控制圖片找不到

如果遇到頁面的圖片載入失敗時,通常會load預設的圖片,避免有叉燒包的情況。
可以自建一個directive來處理此事件

以下是Stackoverflow的解法:
http://stackoverflow.com/questions/16310298/if-a-ngsrc-path-resolves-to-a-404-is-there-a-way-to-fallback-to-a-default


app.directive('errSrc', function() {
  return {
    link: function(scope, element, attrs) {

      scope.$watch(function() {
          return attrs['ngSrc'];
        }, function (value) {
          if (!value) {
            element.attr('src', attrs.errSrc);
          }
      });

      element.bind('error', function() {
        element.attr('src', attrs.errSrc);
      });
    }
  }
})

星期一, 8月 11, 2014

[Angular] MVC MVVM MVP 說文解字

常見的 MVC MVVM MVP 框架說文解字
取自:
https://plus.google.com/+IgorMinar/posts/DRUAkZmXjNV

Igor Minar

公開分享 - 2012年7月19日


MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it'snow closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.




其他討論串:

其他你感興趣的文章

Related Posts with Thumbnails