วันพุธที่ 25 ธันวาคม พ.ศ. 2556

Cheat Sheet : Directives in AngularJS

Controller

$scope.api = {
    onCreate: function(tag) { console.log('add NEW tag', tag); },
    onChange: function(qid, change) { $scope.onTagChange(qid, change); },
}

$scope.testFn = function(obj) {
    console.log('testFn recv ', obj);
}


$scope.onTagChange = function(qid, change) {
    ...
}

Directive

app.directive('chosen',function($parse){
    var linker = function(scope, element, attrs) {
            // example for isolated scope
            console.log(scope.index); // use variable passed from tag
            scope.testFn({obj: change}); // call function with parameter from directive
            scope.api.onChange(scope.question, change); // call function in object passed from tag
            scope.callback()(scope.index, change); // call function passed from tag

            // example for inherited scope
            scope.onTagChange(scope.$index, change); // directly call function from parent scope (in case not using isolated scope)
    };

    return {
        restrict:'A',
        link: linker,
        scope: {index: '=',
                callback: '&chosenChange', // rename in local : chosenChange --> callback
                api: '=chosenApi', // rename in local : chosenApi --> api
                testFn: '&'},
    }

HTML


<div chosen="choice.subtags" chosen-change="onTagChange" chosen-api="api" test-fn= "testFn(obj)" index="$index">

Another Example

Controller

$scope.value = {a: 10};
$scope.inc = function(){
    $scope.value.a += 1;
}
$scope.dec = function(){
    $scope.value.a -= 1;
}

Directive

app.directive('ngSparkline', function() {
  return {
    restrict: 'A',
    scope: {value: '=value', inc: '&incFn', dec: '&decFn'},
    link: linker,
    controller: ['$scope', function($scope) {
        $scope.value8 = $scope.value * 8;
    }],
    template: '<input type="text" ng-model="value8" placeholder="Enter a value" ng-click="inc()" ng-blur="dec()" />',
  }
});

HTML

<div ng-sparkline value="value.a" inc-fn="inc()", dec-fn="dec()"></div>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น