如何从一个AngularJs指令中修改范围 [英] How to modify scope from within a directive in AngularJs

查看:104
本文介绍了如何从一个AngularJs指令中修改范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个指令内的回调中修改根scope属性。但是,该指令是由开关指令创建一个内部范围。

I need to modify a root scope attribute from within a callback inside a directive. But the directive is in a inner scope created by a switch directive.

HTML

<div ng-app="app" ng-controller='AppController'>
    <p>Selected: {{ selected }}</p>
    <div ng-switch on="selected">
        <div ng-switch-default>
            <p>Item: {{ selected }}</p>
            <custom-tag selected-item="selected" />
        </div>
        <div ng-switch-when="New value">
            <p>Worked</p>
        </div>
    </div>
</div>

JavaScript的

JavaScript

angular.module('app', [])    
    .directive("customTag", [function () {
    return {
        restrict: "E",
        replace: true,
        template: "<input type='button' value='Click me' />",

        link: function (scope, element, attrs) {
            element.bind('click', function () {
                scope[attrs.selectedItem] = "New value";
                scope.$apply();
            });
        }
    };
}]);

function AppController($scope) {
    $scope.selected = 'Old value';
}

小提琴: http://jsfiddle.net/nJ7FQ/

我的目标是能够显示的新值。在选定区域。
我怎么能做到什么,我试图做?我在做什么错了?

My objective is to be able to display "New value." in the Selected area. How can I accomplish what I am trying to do? What am I doing wrong?

此外,正如我试图使一个组件..有一种方法可以做到相同,但用孤立的范围是什么?

Besides, as I am trying to make a component.. is there a way to do the same but with a isolated scope?

推荐答案

我更新了小提琴,基本上不得不去父母得到选择正确的变量,也采用了分离范围=拿到之间的双向绑定在传递的值与内部模型

I updated the fiddle, basically had to go to the parent to get the right "selected" variable, also used the isolate scope = to get two way binding between the value passed in and the internal model.

http://jsfiddle.net/nJ7FQ/2/

angular.module('app', [])

    .directive("customTag", [function () {
    return {
        restrict: "E",
        replace: true,
        template: "<input type='button' value='Click me' />",
        scope: {model:'='},

        link: function (scope, element, attrs) {
            element.bind('click', function () {
                scope.model[attrs.selectedItem] = "New value";
                scope.$apply();
            });
        }
    };
}]);

function AppController($scope) {
    $scope.selected = 'Old value';
}

和HTML

<div ng-app="app" ng-controller='AppController'>
    <p>Selected: {{ selected }}</p>
    <div ng-switch on="selected">
        <div ng-switch-default>
            <p>Item: {{ selected }}</p>
            <custom-tag selected-item="selected" model="$parent" />
        </div>
        <div ng-switch-when="New value">
            <p>Worked</p>
        </div>
    </div>
</div>

更新,可使用原来的从属性的属性阅读小提琴:
http://jsfiddle.net/nJ7FQ/4/

这篇关于如何从一个AngularJs指令中修改范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆