javascript - 如何在不同的 View 中使用 ng-model/bind?

标签 javascript angularjs angular-ngmodel

我有一个 app-header View 和正文内容 View ng-view。基本上我在配置文件正文中有一个 ng-model 输入,当它被加载时,我想将它绑定(bind)到标题中的东西。

如果 ng-model 和绑定(bind)在同一个 View 中,我没有问题,但不确定如何让绑定(bind)跨范围:

<!-- Main Nav -->
<app-header></app-header>

<div class="content_container">
    <!-- angular templating content will be injected here -->
    <div ng-view></div>
</div>

在配置文件组件中输入

<input ng-model="profile_name" type="text" id="profile_first_name" name="profile_first_name"/>

标题

<div class="user_badge">{{profile_name}}</div>

header 指令

// Directive for Header
app.directive('appHeader', function () {
    // Type of Directive, E for element, A for Attribute
    // url of a template
    return {
        restrict: 'E',
        templateUrl: 'shared/navigation/header.html'
    };
});

配置文件 Controller

// Controller for Profile
app.controller('ProfileController', function() {
});

// Controller for Complete Registration
app.controller('CompleteRegistrationController', function() {
});

// configure our routes
app.config(['$routeProvider', function($routeProvider) {
    $routeProvider

    // route : Edit Profile
    .when('/profile', {
        title : 'Edit Profile',
        templateUrl : 'components/profile/edit-profile.html',
        controller  : 'ProfileController'
    });
}]);

最佳答案

我猜您遇到了父/子范围界定问题。有一句关于 ng-model 的名言你会经常看到:“如果你没有点,那你就做错了”。这是因为原型(prototype)继承的工作方式。

解决方案是将模型定义为父作用域中的对象。

<input ng-model="profile.name" type="text" />

<div class="user_badge">{{profile.name}}</div>

在父范围内:

$scope.profile = {};

这样,当模型更新时,对父作用域的引用不会被覆盖,但模型数据会更新。

如果您想了解更多关于范围的实际工作原理,请查看 Angular 指南:https://docs.angularjs.org/guide/scope


编辑

这是一个片段,显示它与父/子范围一起工作。它应该与 ng-view 完全相同,只是动态添加 Controller 。

angular.module('test', [])
  .directive('appHeader', function() {
    return {
      restrict: 'E',
      template: '<div class="user_badge">{{profile.name}}</div>'
    };
  })
  .controller('ChildCtrl', function() {
  })
  .controller('ParentCtrl', function($scope) {
    $scope.profile = {
      name: 'Test'
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
  <div ng-controller="ParentCtrl">
    <app-header></app-header>

    <div ng-controller="ChildCtrl">
      <input ng-model="profile.name" type="text" />
    </div>
  </div>
</div>

关于javascript - 如何在不同的 View 中使用 ng-model/bind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26746482/

相关文章:

javascript - Ionic,从侧面菜单隐藏和显示元素

javascript - 从 Controller 以编程方式更改 ngModel 值

javascript - 我的情况使用什么缓存技术?

angularjs - angular 1.5 组件/@binding 的默认值

javascript - 如何在 Safari 调试器中调试延迟加载的 javascript

angularjs - 访问声明函数中的私有(private)变量

angular - 在 Angular Material 表中更改时计算并显示输入字段的总计

javascript - ng-model 未从 Controller 定义

javascript - 根据开始日期和结束日期过滤 JSON

删除许可证的javascript缩小?