angularjs
  • angularjs-directive
  • angularjs-scope
  • 2014-02-16 73 views 0 likes 
    0

    LIVE DEMOAngularJS指令:爲什麼觀察者沒有被觸發?

    考慮以下兩條指令:

    JS:

    angular.module("Directives", []).directive("action", function($compile) { 
        return { 
        restrict: 'A', 
        scope: { 
         action: '=' 
        }, 
        link: function(scope, element) { 
         scope.showDialog = false; 
    
         var template = "<span dialog='showDialog'>Dialog</span>"; 
    
         element.append($compile(template)(scope)).on('click', function() { 
         console.log("Setting showDialog to true"); 
         scope.showDialog = true; 
         }); 
        } 
        }; 
    }).directive("dialog", function() { 
        return { 
        restrict: 'A', 
        scope: { 
         dialog: '=' 
        }, 
        link: function(scope, element) { 
         element.hide(); 
    
         scope.$watch('dialog', function(newValue) { 
         console.log("dialog changed to " + newValue); // Not called on button click 
         }); 
        } 
        }; 
    }); 
    

    HTML:

    <button action>Click Here</button> 
    

    你能解釋一下爲什麼設置actionshowDialog不會觸發dialog「看守人?

    +0

    其實,當你點擊按鈕 - 指令'對話'中的'對話'不會改變 - 看起來不是綁定正確 - 也許是因爲$ compile中的作用域與action-> link中的作用域不同?但我不知道如何解決這個問題。 –

    回答

    2

    .on()是包含在Angular的jqLit​​e中的jQuery方法。附加的事件處理程序中的代碼居住的角度之外,所以你需要使用$apply

    $適用()用於從 角框架之外的角度來執行的表達式。 (例如,來自瀏覽器DOM事件, setTimeout,XHR或第三方庫)。因爲我們正在調用 角度框架,我們需要執行適當的範圍生命週期 異常處理,執行手錶。

    例如:

    element.append($compile(template)(scope)).on('click', function() { 
        scope.$apply(function() { 
        console.log("Toggling showDialog"); 
        scope.showDialog = !scope.showDialog; 
        }); 
    }); 
    

    演示:http://jsbin.com/guziwamu/4/edit

    0

    我做了一些改變寫它的更常見的方法和我移動element.hide();在$表登記後,它能正常工作

    app.directive("action", function ($compile) { 
    function link(scope, element, attrs) {  
        var template = "<span dialog='showDialog'>Dialog</span>"; 
    
        element.append($compile(template)(scope)).on('click', function() { 
         console.log("Setting showDailog to true"); 
         scope.showDailog = !scope.showDailog; 
        }); 
    } 
    
    return { 
        link: link 
    }; 
    }); 
    
    app.directive("dialog", function ($compile) { 
    function link(scope, element, attrs) { 
    
        scope.$watch(attrs.dialog, function (newValue) {    
         console.log("dialog changed to " + newValue); // Not called on button click 
        }); 
    
        element.hide(); 
    } 
    
    return { 
        link: link 
    }; 
    }); 
    

    控制器:

    app.controller('MyController', function ($scope) { 
    
    $scope.showDailog = false; 
    }); 
    

    應用JS:

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

    HTML:

    <button action>Click Here</button> 
         Show dialog: <input data-ng-model="showDailog"> 
    
    +0

    你能否提供一個可用的jsbin? –

    相關問題