AngularJS - 使用时失去范围NG-包括 [英] AngularJS - losing scope when using ng-include

查看:124
本文介绍了AngularJS - 使用时失去范围NG-包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模块路线:

var mainModule = angular.module('lpConnect', []).
    config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/home', {template:'views/home.html', controller:HomeCtrl}).
        when('/admin', {template:'views/admin.html', controller:AdminCtrl}).
        otherwise({redirectTo:'/connect'});
}]);

首页HTML:

<div ng-include src="views.partial1"></div>

partial1 HTML:

partial1 html:

<form ng-submit="addLine()">
    <input type="text" ng-model="lineText" size="30" placeholder="Type your message here">
</form>

HomeCtrl:

HomeCtrl:

function HomeCtrl($scope, $location, $window, $http, Common) {
    ...
    $scope.views = {
        partial1:"views/partial1.html"
    };

    $scope.addLine = function () {
        $scope.chat.addLine($scope.lineText);
        $scope.lines.push({text:$scope.lineText});
        $scope.lineText = "";
    };
...
}

在addLine功能$ scope.lineText是不确定的,这可以通过添加 NG-控制器=HomeCtrl以partial1.html,但它会导致控制器解决被调用两次,是什么我在这里丢失?

in the addLine function $scope.lineText is undefined, this can be resolved by adding ng-controller="HomeCtrl" to partial1.html , however it causes the controller to be called twice, what am I missing here?

推荐答案

这是因为NG-包括创建新的子范围,所以$ scope.lineText不会改变。我认为,这个引用当前范围,所以 this.lineText 应设置。

This is because of ng-include that create a new child scope, so $scope.lineText isn't changed. I think that this refer to the current scope, so this.lineText should be set.

这篇关于AngularJS - 使用时失去范围NG-包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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