在 AngularJS 中更新父作用域变量 [英] Update parent scope variable in AngularJS

查看:28
本文介绍了在 AngularJS 中更新父作用域变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器,一个包裹在另一个中.现在我知道子作用域从父作用域继承属性,但是有没有办法更新父作用域变量?到目前为止,我还没有遇到任何明显的解决方案.

I have two controllers, one wrapped within another. Now I know the child scope inherits properties from the parent scope but is there a way to update the parent scope variable? So far I have not come across any obvious solutions.

在我的情况下,我在表单中有一个日历控制器.我想更新父范围(即表单)的开始和结束日期,以便表单在提交时具有开始和结束日期.

In my situation I have a calendar controller within a form. I would like to update the start and end dates from the parent scope (which is the form) so that the form has the start and end dates when submitted.

推荐答案

您需要在父作用域中使用一个对象(而不是原始对象),然后您将能够直接从子作用域更新它

You need to use an object (not a primitive) in the parent scope and then you will be able to update it directly from the child scope

家长:

app.controller('ctrlParent',function($scope){
    $scope.parentprimitive = "someprimitive";
    $scope.parentobj = {};
    $scope.parentobj.parentproperty = "someproperty";
});

儿童:

app.controller('ctrlChild',function($scope){
    $scope.parentprimitive = "this will NOT modify the parent"; //new child scope variable
    $scope.parentobj.parentproperty = "this WILL modify the parent";
});

工作演示:http://jsfiddle.net/sh0ber/xxNxj/

参见作用域的细微差别是什么AngularJS 中的原型/原型继承?

这篇关于在 AngularJS 中更新父作用域变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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