如何从控制器到自定义指令获取修改后的值?

时间:2016-10-05 06:57:18

标签: angularjs angularjs-directive

我在控制器中定义了一个变量,并且已将此值分配给custom指令的一个属性。所以在这个值的基础上,我展示了模态框模板。现在,如果我从模态框模板中单击取消按钮,则它会从控制器调用一个函数,该函数将变量值修改为false,但它不会隐藏弹出框。请帮我解决。

(function () {
'use strict';

angular.module('module1').directive('myDirective', function () {
    function linkFunction(scope, elem, attrs) {
        //scope.openvalue   = attrs.openvalue;
        scope.closevalue = false;
        scope.close = function () {
            console.log("Inside Close");
            scope.openvalue = false;
            scope.closevalue = false;
        };
    };

    return {
        templateUrl: 'confirmTemplate.html',
        restrict: 'E',
        link: linkFunction,
        scope: {
            confirmtext: '@',
            openvalue: '=',
            closeconfirm: '&',
            submitconfirm: '&'
        },
        controller: ['$scope', function ($scope) {
            $scope.$watch('openvalue', function () {
                console.log("OpenValue : " + $scope.openvalue);
            });
        }]
    };
 });
})();

以下是用于打开此模式的html。

<div class="col-xs-12 options" ng-click="cntrl.flag1 = true">
  <div class="row">
    <myDirective openvalue="cntrl.flag1" confirmtext="This is the text from directive"
                 closeconfirm="cntrl.closeconfirm()" submitconfirm="cntrl.submitconfirm()"></myDirective>
    <div class="col-xs-9 no-left-right-padding">My text</div>
  </div>
</div>

我想在html模板中更新openvalue的值,但它不起作用。

1 个答案:

答案 0 :(得分:0)

这里有你的代码会更清楚,但我认为问题是当你从控制器调用函数时,它实际上并没有修改控制器范围的变量,而是模态的范围

在AngularJS范围内,子范围内的继承变量的任何更改都将创建本地版本。

根据你的话,当你打开一个模态窗口时,它将创建一个新的子范围,当你从控制器调用该函数来修改那个范围变量时,你实际上修改了那个子范围变量而不是控制器。

您可以在控制器和函数中添加console.log($scope.$id);,然后您应该能够看到范围ID不同。

这个Fiddle会给你一个想法,按Esc键关闭模态窗口。但是,正如我所说,让代码解决确切的问题会更好。

根据您的代码,快速修复将cntrl对象分配给指令,这将确保您的指令引用同一个对象。

将您的模态更改为

<myDirective cntrl="cntrl" confirmtext="This is the text from directive"></myDirective>
在你的指令中

scope: {
    confirmtext   : '@',
    cntrl     : '='
},
你的linkFunction

中的

function linkFunction(scope, elem, attrs){
    scope.close = function(){
        scope.cntrl.flag1 = false;
    }

您仍然可以分别通过closeconfirmsubmitconfirm访问$scope.cntrl.closeconfirm$scope.cntrl.submitconfirm