如何在指令控制器中与隔离范围变量进行交互?

And*_*ght 5 angularjs angularjs-directive angularjs-scope

我有指令myDirective,它有一个双向绑定隔离范围.当用户单击按钮时,我想将隔离范围更改为值.我认为隔离范围与$ scope绑定,但我错了.我如何"抓住"并与该隔离范围进行交互?它们是否与指令控制器的范围无关?

angular.module("app", [])
.controller("myCtrl", function($scope){
    $scope.ctrlTwoway = "Eggs";
})
.directive("myDirective", function(){
    return {
        scope: {
          twoway: =
        },
        template: "<button ng-click="changeTwoway()">Change two way isolate scope</button>",
        controller: function($scope, $element, $attrs){
            $scope.changeTwoway = function(){
                // get twoway from isolate scope, and update the value with "bacon"
                // $scope.twoway = "bacon" doesn't work 
                // nor does $attrs.twoway = "bacon" work, either :(
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

和HTML

...
<div my-directive twoway="{{ctrlTwoway}}"></div>
Current value: {{ctrlTwoway}}
Run Code Online (Sandbox Code Playgroud)

Dei*_*zan 10

我创建了一个带有工作版本的plunker .

你不需要把{{variable}}上的twoway="".只需twoway="ctrlTwoway"改为工作.

另一件事是你声明绑定的方式.你正在使用=而不是'='.

另一件事是:尝试在指令中使用链接函数而不是控制器函数.如果你想操纵DOM元素,这是一个很好的做法和正确的地方.

资源

我希望它有所帮助.