亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

AngularJS-將函數傳遞給指令

AngularJS-將函數傳遞給指令

有只小跳蛙 2019-10-08 10:48:50
我有一個angularJS示例<div ng-controller="testCtrl"><test color1="color1" updateFn="updateFn()"></test></div> <script>  angular.module('dr', []).controller("testCtrl", function($scope) {    $scope.color1 = "color";    $scope.updateFn = function() {        alert('123');    }}).directive('test', function() {    return {        restrict: 'E',        scope: {color1: '=',                updateFn: '&'},        template: "<button ng-click='updateFn()'>Click</button>",        replace: true,        link: function(scope, elm, attrs) {         }    }});</script></body></html>我想要當我單擊按鈕時,將出現警報框,但什么也沒顯示。誰能幫我?
查看完整描述

3 回答

?
達令說

TA貢獻1821條經驗 獲得超6個贊

要從隔離作用域指令內部在父作用域中調用控制器功能,請dash-separated在HTML中使用屬性名稱,如OP所述。


另外,如果要向函數發送參數,請通過傳遞對象來調用函數:


<test color1="color1" update-fn="updateFn(msg)"></test>

JS

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


app.controller("testCtrl", function($scope) {

    $scope.color1 = "color";

    $scope.updateFn = function(msg) {        

        alert(msg);

    }

});


app.directive('test', function() {

    return {

        restrict: 'E',

        scope: {

            color1: '=',

            updateFn: '&'

        },

        // object is passed while making the call

        template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>

            Click</button>",

        replace: true,        

        link: function(scope, elm, attrs) {             

        }

    }

});


查看完整回答
反對 回復 2019-10-08
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

在“測試”指令Html標記中,函數的屬性名稱不應為駝峰式,而應基于破折號。


所以-代替:


<test color1="color1" updateFn="updateFn()"></test>

寫:


<test color1="color1" update-fn="updateFn()"></test>

這是angular區分指令屬性(例如update-fn函數)和函數之間差異的方法。


查看完整回答
反對 回復 2019-10-08
  • 3 回答
  • 0 關注
  • 629 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號